1. 程式人生 > >Effective C++ 條款12 賦值物件時勿忘其每一個成分

Effective C++ 條款12 賦值物件時勿忘其每一個成分

請記住:

賦值函式應該確保複製物件內的所有成員變數以及所有基類成分;

例如:

#include<iostream>
using namespace std;
class Base
{
public:
	Base(){}
	Base(int x,int y):ma(x),mb(y){}
	Base(const Base& rhs)
	{
	ma=rhs.ma;
	mb=rhs.mb;
	}
	Base& operator=(const Base&rhs)
	{
		if (this==&rhs)
			return *this;
		ma=rhs.ma;
		mb=rhs.mb;
		return *this;
	}
	virtual void print()
	{
	cout<<"ma= "<<ma<<endl;
	cout<<"mb= "<<mb<<endl;
	}

private:
	int ma;
	int mb;
};


class Derived:public Base
{
public:
	Derived(){}
	Derived(int x,int y,int z,int k):Base(x,y),da(z),db(k){}
	Derived(const Derived& rhs):Base(rhs)
	{
	da=rhs.da;
	db=rhs.db;
	}
	Derived& operator=(const Derived& rhs)
	{
	if (this==&rhs)
		return *this;
	Base::operator =(rhs);
	da=rhs.da;
	db=rhs.db;
		return *this;
	}
	virtual void print()
	{
	Base::print();
	cout<<"da= "<<da<<endl;
	cout<<"db= "<<db<<endl;
	}

private:
	int da;
	int db;

};

int main()
{
	Base b(2,3);
	Derived d(1,2,3,4);
	b.print();
	d.print();
	Derived c=d;
	c.print();
	return 0;
}