在 Internet 上(也特别是在这里,在 stackoverflow 上)有很多返回 *this
的解释代码。
例如来自帖子 Copy constructor and = operator overload in C++: is a common function possible? :
MyClass& MyClass::operator=(const MyClass& other)
{
MyClass tmp(other);
swap(tmp);
return *this;
}
当我将交换写为:
void MyClass::swap( MyClass &tmp )
{
// some code modifying *this i.e. copying some array of tmp into array of *this
}
将 operator =
的返回值设置为 void
并避免返回 *this
还不够吗?
最佳答案
这个习惯用法的存在是为了启用函数调用的链接:
int a, b, c;
a = b = c = 0;
这适用于 int
,因此没有必要让它不适用于用户定义的类型 :)
与流运算符(operator)类似:
std::cout << "Hello, " << name << std::endl;
工作方式与
相同std::cout << "Hello, ";
std::cout << name;
std::cout << std::endl;
由于 return *this
习惯用法,可以像第一个示例一样进行链接。
关于c++ - 为什么有些类方法返回 "*this"(自身的对象引用)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36571515/