概述
- 赋值操作符函数模仿内置类型的赋值操作
- 赋值操作符函数只是赋值操作符重载的一个特殊版本,其形参列表为[const] classname &,当实例对象赋值操作时调用
辅助类
class CAnimal
{
public:
CAnimal() : mGroup(0)
{
cout << "CAnimal()" << endl;
}
CAnimal(int group) : mGroup(group)
{
cout << "CAnimal(" << group << ")" << endl;
}
CAnimal(const CAnimal &other) : mGroup(other.mGroup)
{
cout << "CAnimal(const CAnimal &other)" << endl;
}
~CAnimal()
{
cout << "~CAnimal()" << endl;
}
public:
CAnimal& operator=(const CAnimal &other)
{
mGroup = other.mGroup;
cout << "CAnimal operator=" << endl;
return *this;
}
private:
int mGroup;
};
class CDog : public CAnimal
{
public:
CDog() : mLoyal(10)
{
cout << "CDog()" << endl;
}
CDog(int loyal) : CAnimal(1), mLoyal(loyal)
{
cout << "CDog(" << loyal << ")" << endl;
}
CDog(const CDog &other) : CAnimal(other), mLoyal(other.mLoyal)
{
cout << "CDog(const CDog &other)" << endl;
}
~CDog()
{
cout << "~CDog()" << endl;
}
public:
CDog& operator=(const CDog &other)
{
CAnimal::operator=(other);
mLoyal = other.mLoyal;
cout << "CDog operator=" << endl;
return *this;
}
private:
int mLoyal;
};
class CCat : public CAnimal
{
public:
CCat() : mCute(20)
{
cout << "CCat()" << endl;
}
CCat(int cute) : CAnimal(2), mCute(cute)
{
cout << "CCat(" << cute << ")" << endl;
}
CCat(const CCat &other) : CAnimal(other), mCute(other.mCute)
{
cout << "CCat(const CCat &other)" << endl;
}
~CCat()
{
cout << "~CCat()" << endl;
}
public:
CCat& operator=(const CCat &other)
{
CAnimal::operator=(other);
mCute = other.mCute;
cout << "CCat operator=" << endl;
return *this;
}