请记住:
赋值函数应该确保复制对象内的所有成员变量以及所有基类成分;
例如:
#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;
}