简体   繁体   English

为什么我们必须从一元前缀运算符重载中返回const引用

[英]why do we have to return const reference from unary prefix operator overloading

I have one doubt on prefix operator overloading . 我对前缀运算符重载有疑问。

my sample program: 我的示例程序:

class ABC {
    int i;
public:
    const ABC& operator++() { i=i+1; return *this;}
};

int main() {
    ABC ob ; //let value of i =5;
    ++ob;  // value of i will be 6
    return 0;
}

but I could do the same thing by overloading like below 但是我可以通过如下所示的重载来做同样的事情

void operator++() { i=i+1;}

this gives me same result when calling ++ob 这在调用++ob时给我相同的结果

APMK ++ob converted as ob.operator++() . APMK ++ob转换为ob.operator++()

My doubt is what happens to the return value. 我的疑问是返回值会如何变化。 Does the compiler creates code like: 编译器是否创建如下代码:

ob = ob.operator++();

Thanks in advance 提前致谢

why do we have to return const reference from unary prefix operator overloading 为什么我们必须从一元前缀运算符重载中返回const引用

You don't have to. 不用了 Typically you return non-const reference, but you could make it return anything. 通常,您返回非常量引用,但是您可以使其返回任何内容。 You shouldn't, but you could. 您不应该,但是可以。 The built in pre-increment works how returning non-const reference works, so it makes the most sense to do that. 内置的预递增功能可用于返回非const引用的工作方式,因此这样做最有意义。

The reason to return a reference to an object is to make the behavior the same as for integers (for built in types). 返回对对象的引用的原因是使行为与整数(对于内置类型)相同。

std::cout << ++i;
std::cout << i++;

If i is an integer this will work. 如果i是一个整数,它将起作用。 This will only work in a class if you return a reference to the object (Assuming you have defined operator<< for your class). 如果您返回对对象的引用(假设您为类定义了operator<< ,则这仅在类中有效。

class ABC {
    int i;
public:
    ABC(int x = 0) : i(x) {}
    const ABC& operator++()    { i=i+1; return *this;}
          ABC  operator++(int) { ABC result(*this);i=i+1; return result;}
    friend std::ostream& operator<<(std::ostream& out, ABC const& val)
    {
        return out << val.i;
    }
};

With this definition then your class will behave the same way that an integer will behave in the above situation. 使用此定义,您的类的行为将与上述情况下整数的行为相同。 Which makes it very useful when using template as you can now do a drop in replacement for integer with your type. 这在使用模板时非常有用,因为您现在可以用类型替换整数。

Note normally I would return just a reference (not a const reference). 注意,通常我只会返回一个引用(而不是const引用)。

/*const*/ ABC& operator++()    { i=i+1; return *this;}
^^^^^^^^^

see: https://stackoverflow.com/a/3846374/14065 参见: https : //stackoverflow.com/a/3846374/14065

But C++ allows you do anything and you can return whatever is useful or has appropriate meaning for the situation. 但是C ++允许您执行任何操作,并且可以返回对情况有用或有意义的任何东西。 You should consider what is meaningful for your class and return a value that is appropriate. 您应该考虑什么对您的班级有意义,并返回适当的值。 Remember the Principle of lease surprise 记住租赁惊奇原则

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM