为什么有些类方法返回"*this"(self的对象引用)?

sca*_*ace 6 c++ this return-value

在互联网上有很多代码可以解释(特别是在这里,在stackoverflow上)*this.

例如,来自复制构造函数和C++中的=运算符重载:可能是一个常见的函数吗?:

MyClass& MyClass::operator=(const MyClass& other)
{
    MyClass tmp(other);
    swap(tmp);
    return *this;
}
Run Code Online (Sandbox Code Playgroud)

当我把swap写为:

void MyClass::swap( MyClass &tmp )
{
  // some code modifying *this i.e. copying some array of tmp into array of *this
}
Run Code Online (Sandbox Code Playgroud)

是不是足够设定返回值operator =,以void避免回国*this

Mag*_*off 9

这个成语存在以启用函数调用的链接:

int a, b, c;
a = b = c = 0;
Run Code Online (Sandbox Code Playgroud)

这适用于ints,所以没有必要让它不适用于用户定义的类型:)

同样对于流运营商:

std::cout << "Hello, " << name << std::endl;
Run Code Online (Sandbox Code Playgroud)

与...一样的工作

std::cout << "Hello, ";
std::cout << name;
std::cout << std::endl;
Run Code Online (Sandbox Code Playgroud)

由于这个return *this成语,它可以像第一个例子一样链.


Geo*_*tov 7

*this返回的原因之一是允许赋值链a = b = c;等同于b = c; a = b;.通常,赋值结果可以在任何地方使用,例如在调用函数(f(a = b))或表达式(a = (b = c * 5) * 10)时.虽然,在大多数情况下,它只会使代码更复杂.