c++ - 为什么有些类方法返回 "*this"(自身的对象引用)?

标签 c++ this return-value

在 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/

相关文章:

c++ - 命名空间的多个别名?

c++ - 将大量数字 vector 保存到硬盘驱动器

c++ - 如何从仅提供复制构造函数的类实例化 "empty"对象?

javascript - 如何获取调用函数/对象的上下文?

javascript - 在 jQuery 淡入中使用 'this' 变量?

javascript - 这不返回对象属性(箭头,this)

error-handling - "special"返回值如何表示调用的条件?

c++ - OpenGL - 每个三角形的像素数不正确

powershell - 等待 PsExec 在 PowerShell 中调用 cmd/c 完成

php - 在 WordPress 中返回当前 URL