派生类的拷贝中记得拷贝基类的内容(手写的话)

如果你没有new,可以使用默认的拷贝构造函数和默认的operator=,她会自动帮你完善

手写拷贝使用的两个函数

1,拷贝构造函数

2,operator=函数

class A
{
public:
	int a;
	A(int x) :a(x){};
};

class B:public A
{
private:
	int b;
public:
	B(int x, int y) :A(x), b(y){}
	B(const B& x) :A(x), b(x.b){}//1.可以模仿构造函数。2.由于调用了A(x),不需要另外写a(x.a)
	B& operator=(const B& x)
	{
		A::operator=(x);//operator=拷贝父类
		b = x.b;
		return *this;
	}
	void display()
	{
		cout << a <<" "<< b << endl;
	}

};

int main()
{
	B a(1,3);
	a.display();
	B b(2, 3);
	b.display();
	b = a;          //测试operator=函数
	b.display();
	B c(a);          //测试拷贝构造函数
	c.display();
}

  

posted on 2016-06-14 18:59  Kooing  阅读(358)  评论(0编辑  收藏  举报

导航