为什么在带有多个参数的重载运算符+中传递const引用 [英] Why pass by const reference in overload operator+ with multiple parameters

查看:250
本文介绍了为什么在带有多个参数的重载运算符+中传递const引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用多个参数进行operator +重载.

I am doing operator+ overloading with multiple parameters as below.

#include <iostream>
using namespace std;
class Integer{
    int value;
    public:
        Integer(int i) {value=i;};
        int getValue() { return value;};
        friend Integer operator+ (Integer & a, Integer & b){
            Integer I (a.value+b.value);
            return I;
        };
};

int main() {
    Integer a(1), b(2), c(3);
    Integer d = a+b+c;
    cout<<d.getValue()<<endl;
    return 0;
}

不能编译并返回运算符+不匹配".我阅读并理解了((a + b)+ c)多参数的算法.为什么不起作用? 但是,我发现了两种使它起作用的方法:

It can't be compile and return" no match for operator+". I read and understand the algorithm of multiple parameter that ((a+b)+c). Why it does not work? However, I found two ways to make it work:

friend Integer operator+ (const Integer & a,const Integer & b){
    Integer I (a.value+b.value);
    return I;
};

还有

friend Integer & operator+ (Integer & a,Integer & b){
    Integer I (a.value+b.value);
    return I;
};

但是我不知道为什么.谢谢

But I dont know why. Thank you

推荐答案

查看您的operator+签名:

friend Integer operator+ (Integer & a, Integer & b)
//                        ^^^^^^^^^    ^^^^^^^^^

ab左值引用.

写作时

Integer d = a+b+c;

a+b产生类型为Integer rvalue ,该值不绑定到Integer&.

a+b produces an rvalue of type Integer, which does not bind to Integer&.

带有const Integer &的版本可用作const左值引用,可以绑定到左值右值.

The version with const Integer & works as const lvalue references can be bound to both lvalues and rvalues.

这篇关于为什么在带有多个参数的重载运算符+中传递const引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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