C++ 识别运算符 = 的不同

标签 c++

<分区>

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 的引用。

关于C++ 识别运算符 = 的不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23173630/

相关文章:

c++ - 在 C++ 中创建链表

c++ - Bison/Flex 以相反的顺序处理 token

c++ - 禁用 "Processing/ORDER options..."的 MSBuild 输出

c++ - 目录相对 ZwCreateFile

c++ - 在另一个线程 visual studio 2012 中看不到 std::string 的变化

c++ - 将容器与 GoogleTest 进行比较

c++ - 无法导出模板函数

c++ - 在 Vista/7 (C++) 上获取音量变化通知

c++ - 具有怪异行为的井字游戏Minimax算法(C++)

c++ - 使用 C++ 和 WinAPI 在 Windows 8 上登录用户名或电子邮件