mac*_*ard 19 c++ operator-overloading return-type assignment-operator
我正在修改我的C++,我正在处理运算符重载,特别是"="(赋值)运算符.我在网上看到并且遇到了讨论它的多个主题.在我自己的笔记中,我把所有的例子都记下来了
class Foo
{
public:
int x;
int y;
void operator=(const Foo&);
};
void Foo::operator=(const Foo &rhs)
{
x = rhs.x;
y = rhs.y;
}
Run Code Online (Sandbox Code Playgroud)
在我在网上找到的所有参考文献中,我注意到操作符返回对源对象的引用.为什么返回对象的引用的正确方法而不是什么都没有?
Mat*_*lia 19
通常的表单返回对目标对象的引用以允许赋值链接.否则,将无法做到:
Foo a, b, c;
// ...
a = b = c;
Run Code Online (Sandbox Code Playgroud)
尽管如此,请记住,正确使用分配操作员比看起来更难.
Bor*_*lid 14
当您只是在如下语句中执行单个赋值时,返回类型无关紧要:
x = y;
Run Code Online (Sandbox Code Playgroud)
当你这样做时,它开始变得重要:
if ((x = y)) {
Run Code Online (Sandbox Code Playgroud)
......当你这样做时真的很重要:
x = y = z;
Run Code Online (Sandbox Code Playgroud)
这就是你返回当前对象的原因:允许链接具有正确关联性的赋值.这是一个很好的通用做法.
您的赋值运算符应始终执行以下三项操作:
将const-reference输入(const MyClass &rhs)作为赋值的右侧.其原因应该是显而易见的,因为我们不想意外地改变这个价值; 我们只想改变左侧的内容.
始终返回对新改变的左侧的引用,return *this.这是为了允许操作员链接,例如a = b = c;.
始终检查自我分配(this == &rhs).当您的类执行自己的内存分配时,这一点尤为重要.
MyClass& MyClass::operator=(const MyClass &rhs) {
// Check for self-assignment!
if (this == &rhs) // Same object?
return *this; // Yes, so skip assignment, and just return *this.
... // Deallocate, allocate new space, copy values, etc...
return *this; //Return self
}
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
11409 次 |
| 最近记录: |