美文网首页
第二周 作业 C++工程师 Boolan

第二周 作业 C++工程师 Boolan

作者: 一般的路人丙 | 来源:发表于2017-02-08 22:03 被阅读0次

题目

为 Rectangle 类实现构造函数,拷贝构造函数,赋值操作符,析构函数。

class Shape {
  int no;
};
class Point {
  int x;
  int y;
};
class Rectangle : public Shape {
  int width;
  int height;
  Point *leftUp;

public:

  Rectangle(int width,
            int height,
            int x,
            int y);
  Rectangle(const Rectangle& other);
  Rectangle& operator=(const Rectangle& other);
  ~Rectangle();
};
  • 作业要求:
    一,请使用正规编码风格。
    二,所有代码写在.h 和.cpp文件中,不要写在word或txt等文件中。
    三,请将作业以附件上传的形式提交,请用你的Boolan账号昵称命名文件夹。

分析代码

  1. 首先,有一个叫 Shape 的类,这个类的值只有一个,是整型。应该是通过这个值判断是什么样的形状,比如1是矩形。
  2. 然后,有一个叫 Point 的类,这个类有两个值,很明显是坐标。
  3. 然后有个矩形的类,这个类和 Shape 有关系,不明白是什么关系。下面有宽高两个参数,还有一个指向点的指针。可以看到,构造函数和 Big Three。

开工

  1. 首先,Shape 这段,并没有发生问题,所以不管也没有关系。
class Shape {
public:
    Shape(int n = 1) : no(n) {}
    int shc() const {
      return no;
  }
private:
    int no;
};

只是改成了更容易看的格式。

  1. 然后是 Point 部分,一开始还是以是 pointer,后来写代码时才反应过来,原来是点。二维空间的点和复数的写法是一样一样的。只写了类定义和赋值重载。
class Point {
public:
    Point(int xx = 0, int yy = 0) : x(xx), y(yy) {}
    Point operator=(const Point pt);
    int   getx() const {
      return x;
  }
  int gety() const {
      return y;
  }
private:
    int x;
    int y;
};
inline Point
Point::operator=(const Point pt) {
    x = pt.y;
    y = pt.y;
    return Point(x, y);
}
  1. 接下来啃这次的重点 Rectangle。首先是构造函数。
inline
Rectangle::Rectangle() {
    width   = 0;
    height  = 0;
    *leftUp = Point(0, 0);
}
inline
Rectangle::Rectangle(int w, int h) {
    width   = w;
    height  = h;
    *leftUp = Point(0, 0);
}
inline
Rectangle::Rectangle(int w, int h, const Point pt) {
    width   = w;
    height  = h;
    *leftUp = pt;
}

一开始只写了最后一个构造函数,后来发现新建空的矩形时不方便,于是又写了前两个。

  1. 然后是析构函数。
inline
Rectangle::~Rectangle() {
    delete leftUp;
}

一开始并不太理解为什么要 delete,后来发现是课上讲过,但是忘了。

  1. 最后是赋值操作符。
inline Rectangle&
Rectangle::operator=(const Rectangle& other) {
    if (this == &other) return *this;
    width   = other.getw();
    height  = other.geth();
    *leftUp = *other.getp();
    return *this;
}

这段一开始出了大问题,表现出来的是 Point不能赋值,后来确定是*leftUp 这种形式不能复制,看了结果,发现是指针指向的地址未分配,后来搜索了一下,才发现应该用 new 新建一个空间,对应String 里面的m_data = new char[1];,所以应该在定义 leftUp 的时候,加上 new Point()

  1. 最后类定义是这样的:
class Rectangle : public Shape {
public:
    Rectangle(int         w,
              int         h,
              const Point pt);
    Rectangle(int w,
              int h);
    Rectangle();
    Rectangle(const Rectangle& other);
    Rectangle& operator=(const Rectangle& other);
    ~Rectangle();
    int getw() const {
      return width;
    }
    int geth() const {
      return height;
    }
    Point* getp() const {
      return leftUp;
    }
private:
    int width;
    int height;
    Point *leftUp = new Point();
};

相关文章

网友评论

      本文标题:第二周 作业 C++工程师 Boolan

      本文链接:https://www.haomeiwen.com/subject/hixbittx.html