C中的赋值运算符重载 [英] assignment operator overloading in c++

查看:95
本文介绍了C中的赋值运算符重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 ?

推荐答案

第二版赋值运算符没有问题.实际上,这是赋值运算符的标准方法.

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.

这篇关于C中的赋值运算符重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆