C ++中的重载赋值运算符的返回类型 [英] return type of overloading assignment operator in c++

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

问题描述

可能重复:
为什么复制分配运算符必须返回参考/const参考?
Operator = C ++中的重载

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.

我的类声明是这样的:

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:
};

我的班级定义:

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;
}

当我们处理"itsRadius = rhs.getRadius()"之类的当前对象时,当前对象的半径将被更改,那么,返回"* this"的需求是什么?可以将此功能重写为void吗?有什么问题吗?还是只是遵循的标准?

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 ?

推荐答案

遵循良好的约定,以与operator=的内置类型的行为保持一致.

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;

如果您不将引用返回给*this,则您的类型将不支持分配链.

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

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

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