构造函数、拷贝构造函数、赋值操作符
对于这样一种类与类之间的关系,我们希望为其编写“深拷贝”。两个类的定义如下:
class Point { int x; int y; }; class Polygon : public Shape { Point *points; };
1. 构造函数
//构造函数 Polygon(const Point &p) : _point(new Point) { this->_point->x = p.x; this->_point->y = p.y; }
2. 拷贝构造函数
//拷贝构造 Polygon(const Polygon &p) : _point(new Point) { this->_point->x = p._point->x; this->_point->y = p._point->y; }
3. 赋值构造函数
//赋值操作符 void operator= (const Polygon &rhs) { this->_point->x = rhs._point->x; this->_point->y = rhs._point->y; }
全部代码 & 测试用例
#include <iostream> using namespace std; struct Shape { int no; //形状编号 }; struct Point { int x; int y; Point(int x, int y) : x(x), y(y) {} Point() = default; }; struct Polygon :public Shape { Point *_point; //构造函数 Polygon(const Point &p) : _point(new Point) { this->_point->x = p.x; this->_point->y = p.y; } //拷贝构造 Polygon(const Polygon &p) : _point(new Point) { this->_point->x = p._point->x; this->_point->y = p._point->y; } //赋值操作符 void operator= (const Polygon &rhs) { this->_point->x = rhs._point->x; this->_point->y = rhs._point->y; } ~Polygon() { delete this->_point; } }; int main() { Point x1(1, 2); Polygon p1(x1); Polygon p2 = p1; Polygon p3(p2); p1 = p2; return 0; }
内存中变量地址
p1 . _ponit 内存地址 0x002c0cb8
p2 . _point 内存地址 0x002c0cf0
p3 . _point 内存地址 0x002c0d28
(都是不相同的内存地址)
成功
智慧在街市上呼喊,在宽阔处发声。