MyClass& operator=(const MyClass& other)
{
//Implement
return *this;
}
MyClass operator=(const MyClass& other)
{
//Implement
return *this;
}
void operator=(const MyClass& other)
{
//Implement
}
当我测试这些方法时,结果是一样的。在几乎一本书中,我看到第一种方法(MyClass&)比第二种方法使用得更多。他们之间有什么不同?哪种方法真正正确且快速?一个方法返回地址和第二个返回值。
When I test these methods, the result is the same.
这取决于你如何测试你的类(class),即:
void foo (MyClass& a);
MyClass a1;
MyClass a2;
foo(a1 = a2);
如果是第二个运算符实现(返回 MyClass
),上面的代码(在 foo
内)不会修改 a1
实例,而是一个临时的值(value)。
In almost book I see that the first method(MyClass&) is used more than
the second method.
没错,在赋值运算符中返回对*this
的引用更正确
what's different between them? Which method is really right and fast?
第一个版本更快更正确,因为它不做你的对象的任何拷贝,而且它更合适,因为这就是原始类型的行为方式,即:
int n = 0;
int k = 10;
(n = k) = 1;
std::cout << n;
这里输出你会得到 1,因为 (n = k)
返回对 n
的引用。