return type of overloading assignment operator in

2019-06-25 12:36发布

Possible Duplicate:
Why must the copy assignment operator return a reference/const reference?
Operator= overloading in C++

I have already asked a question about this assignment operator overloading. I may be asking a foolish question. Pardon me.

My class declaration is like this:

class Circle
{
    public:
       Circle();
       Circle(const Circle &);
       Circle(unsigned short rad);
       unsigned short getRadius() const { return itsradius; }
       void setRadius(unsigned short rad) { itsRadius = rad; }
    private:
       unsigned short itsRadius:
};

My class definition:

Circle::Circle()
{
   itsRadius = 0;
}
Circle::Circle(unsigned short rad)
{
   itsRadius = rad;
}
Circle::Circle(const Circle & rhs)
{
   itsRadius = rhs.getRadius();
}

I am overloading assignment operator like this:

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

When we are working on the current object like "itsRadius = rhs.getRadius()", the current object's radius will be changed, then, what is the need for returning "*this" ? Can this function be re-written as a void one ? Is there any problem with it ? Or is it just a standard to follow ?

4条回答
Bombasti
2楼-- · 2019-06-25 13:07

It allows you to assign to multiple instances in one statement like this:

s1 = s2 = s3;
查看更多
干净又极端
3楼-- · 2019-06-25 13:09

Returning *this allows you to chain assignments like this,

SimpleCircle a, b, c(10);
a = b = c;
查看更多
我想做一个坏孩纸
4楼-- · 2019-06-25 13:16

It's convention, see wikipedia, and the linked article by Richard Gillam.

查看更多
仙女界的扛把子
5楼-- · 2019-06-25 13:18

That is a good convention to follow to be consistent with the behavior of operator= for built-in types.

With built-in types you can do something like this:

int a, b, c;
// ...
a = b = c = 10;

If you do not return the reference to *this, the assignment chain won't be supported by your type.

查看更多
登录 后发表回答