C ++中的赋值运算符重载

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10076285/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 13:35:17  来源:igfitidea点击:

assignment operator overloading in c++

c++operator-overloading

提问by kaushik

I have used the following code for assignment operator overloading:

我使用以下代码进行赋值运算符重载:

SimpleCircle SimpleCircle::operator=(const SimpleCircle & rhs)
{
     if(this == &rhs)
        return *this;
     itsRadius = rhs.getRadius();
     return *this;
}

My Copy Constructor is this:

我的复制构造函数是这样的:

SimpleCircle::SimpleCircle(const SimpleCircle & rhs)
{
    itsRadius = rhs.getRadius();
}

In the above operator overloading code, copy constructor is called as there is a new object is being created; hence I used the below code:

在上面的运算符重载代码中,复制构造函数在创建新对象时被调用;因此我使用了以下代码:

SimpleCircle & SimpleCircle::operator=(const SimpleCircle & rhs)
{
    if(this == &rhs)
       return *this;
    itsRadius = rhs.getRadius();
    return *this;
}

Its working perfectly and the copy constructor problem is avoided, but is there any unknown issues (to me) regarding this ?

它完美地工作并且避免了复制构造函数问题,但是关于这个有任何未知的问题(对我来说)吗?

采纳答案by juanchopanza

There are no problems with the second version of the assignment operator. In fact, that is the standard way for an assignment operator.

赋值运算符的第二个版本没有问题。事实上,这是赋值运算符的标准方式。

Edit: Note that I am referring to the return type of the assignment operator, not to the implementation itself. As has been pointed out in comments, the implementation itself is another issue. See here.

编辑:请注意,我指的是赋值运算符的返回类型,而不是实现本身。正如评论中指出的那样,实现本身是另一个问题。见这里

回答by AJG85

The second is pretty standard. You often prefer to return a reference from an assignment operator so that statements like a = b = c;resolve as expected. I can't think of any cases where I would want to return a copy from assignment.

第二个很标准。您通常更喜欢从赋值运算符返回一个引用,以便像a = b = c;预期的那样解析语句。我想不出任何我想从作业中返回副本的情况。

One thing to note is that if you aren't needing a deep copy it's sometimes considered best to use the implicit copy constructor and assignment operator generated by the compiler than roll your own. Really up to you though ...

需要注意的一件事是,如果您不需要深层复制,有时认为最好使用编译器生成的隐式复制构造函数和赋值运算符,而不是自己动手。不过真的取决于你...

Edit:

编辑:

Here's some basic calls:

以下是一些基本调用:

SimpleCircle x; // default constructor
SimpleCircle y(x); // copy constructor
x = y; // assignment operator

Now say we had the first version of your assignment operator:

现在假设我们有你的赋值运算符的第一个版本:

SimpleCircle SimpleCircle::operator=(const SimpleCircle & rhs)
{
     if(this == &rhs)
        return *this; // calls copy constructor SimpleCircle(*this)
     itsRadius = rhs.getRadius(); // copy member
     return *this; // calls copy constructor
}

It calls the copy constructor and passes a reference to thisin order to construct the copy to be returned. Now in the second example we avoid the copy by just returning a reference to this

它调用复制构造函数并传递一个引用this以构造要返回的副本。现在在第二个例子中,我们通过只返回一个引用来避免复制this

SimpleCircle & SimpleCircle::operator=(const SimpleCircle & rhs)
{
    if(this == &rhs)
       return *this; // return reference to this (no copy)
    itsRadius = rhs.getRadius(); // copy member
    return *this; // return reference to this (no copy)
}

回答by Jerry Coffin

Under the circumstances, you're almost certainly better off skipping the check for self-assignment -- when you're only assigning one member that seems to be a simple type (probably a double), it's generally faster to do that assignment than avoid it, so you'd end up with:

在这种情况下,您几乎肯定最好跳过自分配检查——当您只分配一个似乎是简单类型(可能是双精度)的成员时,执行该分配通常比避免分配要快它,所以你最终会得到:

SimpleCircle & SimpleCircle::operator=(const SimpleCircle & rhs)
{
    itsRadius = rhs.getRadius(); // or just `itsRadius = rhs.itsRadius;`
    return *this;
}

I realize that many older and/or lower quality books advise checking for self assignment. At least in my experience, however, it's sufficiently rare that you're better off without it (and if the operator depends on it for correctness, it's almost certainly not exception safe).

我意识到许多较旧和/或质量较低的书籍建议检查自我分配。然而,至少根据我的经验,没有它你会更好(如果操作员依赖它的正确性,它几乎肯定不是异常安全的)是非常罕见的。

As an aside, I'd note that to define a circle, you generally need a center and a radius, and when you copy or assign, you want to copy/assign both.

顺便说一句,我会注意到要定义一个圆,您通常需要一个中心和一个半径,并且当您复制或分配时,您希望同时复制/分配两者。

回答by Andy_aka_mol

it's right way to use operator overloading now you get your object by reference avoiding value copying.

这是使用运算符重载的正确方法,现在您可以通过引用获取对象,避免值复制。

回答by user2808359

this might be helpful:

这可能会有所帮助:

// Operator overloading in C++
//assignment operator overloading
#include<iostream>
using namespace std;

class Employee
{
private:
int idNum;
double salary;
public:
Employee ( ) {
    idNum = 0, salary = 0.0;
}

void setValues (int a, int b);
void operator= (Employee &emp );

};

void Employee::setValues ( int idN , int sal )
{

salary = sal; idNum = idN;

}

void Employee::operator = (Employee &emp)  // Assignment operator overloading function
{
salary = emp.salary;
}

int main ( )
{

Employee emp1;
emp1.setValues(10,33);
Employee emp2;
emp2 = emp1; // emp2 is calling object using assignment operator

}