构造/析构/赋值运算符
条款10 令operator= 返回一个reference to *this
关于赋值,可以写成连锁赋值形式 ,如 x = y = z = 4
如果是用户自定义的数据类型class, 要如何实现?
class Cat
{
public:
Cat(std::string name="mimi", int age = 3):name_(name),age_(age){}
~Cat() {}
/*
Cat &operator=(const Cat &rhs)
{
this->name_ = rhs.name_;
this->age_ = rhs.age_;
return *this;
}
*/
void operator=(const Cat &rhs)
{
this->name_ = rhs.name_;
this->age_ = rhs.age_;
return ;
}
int operator=(const int age)
{
this->age_ = age;
return this->age_;
}
void Print() {std::cout << "name " << name_ << " age = " << age_ << std::endl;}
private:
std::string name_;
int age_;
};
int main()
{
Cat A("miaomiao",3);
Cat B ,C;
C = A ; //ok
B = A ; //ok
C = B = A ;//error ,若采用return *this的,则是ok的。
C = B = A = 3; // ok
}
本条款并无强制性,如果不遵循,一样可以通过编译。
如上例中返回是void 类型时,需要分两步。若返回值是int,(参数也是int),则可以实现连锁赋值。
故个人觉得更准确的说法应该是令operator= 返回一个和参数类型一样的值。只不过大部分情况下,operator=的参数为一个同类对象的reference.