C++ geekband homework review 2

C++极客班作业第二题

为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();

};

头文件

#ifndef _RECTANGLE_

#define _RECTANGLE_

class Shape

{

int no;

};

class Point

{

int x;

int y;

};

当时为了测试,我在此处添加了一个Rectlangle的友元,仍然是因为对类的构造函数和拷贝构造函数没有理解透彻。

class Rectangle:public Shape

{

public:

int Width()  const{ return width;  }

Rectangle(int w = 0, int h = 0, int x = 0, int y = 0);

Rectangle(const Rectangle& other);

Rectangle& operator = (const Rectangle& other);

~Rectangle();

private:

int width;

int height;

Point* leftup;

};

构造函数

inline

Rectangle::Rectangle(int w,int h,int x,int y)

:width(w)

,height(h)

{

leftup = new Point();

//不添加友元,此处提示不能访问私有成员

leftup->x = x;

leftup->y = y;

}

修改后的代码

inline

Rectangle::Rectangle(int w,int h,int x,int y)

:width(w)

,height(h)

{

leftup = new Point();

}

为什么此处可以实现呢?因为编译器为Point提供了默认的构造函数,Point内部的数据非常简单,编译器进行逐个赋值即可满足题目中的要求。

拷贝赋值函数

inline

Rectangle& Rectangle::operator = (const Rectangle& other)

{

if (this == &other)

{

return *this;

}

width = other.width;

height = other.height;

delete leftup;

leftup = new Point();

leftup = new Point(*other->leftup);

leftup->x = other.leftup->x;

leftup->y = other.leftup->y;

return *this;

}

此处我首先对this->leftup进行了删除,当时李老师说不需要去删除,但是侯杰老师多次强调要删除。我当时在想这两位大师肯定有一位犯错误了,事实证明大师不是随便能被怀疑的,两位大师都是对的。---侯杰老师强调删除是因为后续进行的是指针对象的赋值,李老师说不需要删除是因为李老师后续进行了对象的赋值。看来课程还得多听几遍,大师的话真是字字珠玑啊!

另:李老师在此处的讲解中有一点小错误---other->leftup

修改后

inline

Rectangle& Rectangle::operator = (const Rectangle& other)

{

if (this == &other)

{

return *this;

}

if (other.leftup != NULL)

{

leftup = new Point(*(other.leftup));

}

else

{

this->leftup = NULL;

}

width = other.width;

height = other.height;

Shape::operator = (other);

return *this;

}

拷贝构造函数

inline

Rectangle::Rectangle(const Rectangle& other)

{

width = other.width;

height = other.height;

leftup = new Point();

leftup->x = other.leftup->x;

leftup->y = other.leftup->y;

}

此处的问题较大:

没有判断other.leftup是否为空

应该使用拷贝构造函数,防止Point扩容的问题

没有考虑父类(Shape)

修改后

inline

Rectangle::Rectangle(const Rectangle& other)

:Shape(other)

,width(other.width)

,height(other.height)

{

if (other.leftup != NULL)

{

leftup = new Point(*other.leftup);

}

else

{

leftup = NULL;

}

}

析构函数

inline

Rectangle::~Rectangle()

{

delete leftup;

}

#endif

源文件

#include

#include "Rectangle2.h"

using namespace std;

int main(int argc, char* argv[])

{

Rectangle rect(100,100,10,10);

Rectangle rect2(rect);

Rectangle rect3;

rect3 = rect2;

cout<

return 0;

}

测试结果

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容