c++ - 为什么在后面的运算符重载中需要使用const?

标签 c++

这是添加 3 个 Integer 类对象的代码

#include <iostream>
using namespace std;
class Integer
{
    int value;
    public:
    Integer(int i) 
    { 
        value = i; 
    };
    int getValue() 
    { 
        return value; 
    }
    friend Integer operator+(const Integer & a,const Integer & b)
    {
        Integer i(a.value+b.value);
        return i;
    }
};
int main()
{
    Integer a(1), b(2), c(3);
    Integer d = a + b + c; //****HERE****
    cout << d.getValue() << endl;
    return 0;
}

有人可以解释为什么在这种情况下将 const 添加到参数中。如果我删除 const,在编译期间我会得到 invalid operands to binary operation 错误。 添加到这个问题: 当我只添加 a 和 b 而没有 const 时,输出是 3 没有任何错误。但是,添加 3 个 a+b+c 对象时,出现错误。这是为什么?

最佳答案

假设我们编写了这个函数:

friend Integer operator+(Integer& a, Integer& b);

在风格上,这不是很好,因为 operator+ 不应该修改它的参数。但是假设我们不关心这个。现在,当我们尝试这样做时会发生什么:

Integer d = a + b + c;

这被分组为 (a+b)+ca+b 子表达式将找到我们的 operator+(),这是一个可行的函数,因为 abInteger 类型的非 const 左值,并且该表达式的结果是 Integer 类型的右值。

随后的表达式是{some rvalue Integer} + c那个 表达式我们将无法为其找到可行的函数。虽然 c 可以绑定(bind)到 Integer&,但第一个参数不能 - 您不能将右值绑定(bind)到非 const 左值引用。所以你必须写这样的东西:

Integer tmp = a + b; // OK
Integer d = tmp + c; // also OK

但现在我们将这个额外的名称引入我们的范围,并在我们的代码中引入一个额外的语句,只是为了解决我们函数签名的不可行性问题。

关于c++ - 为什么在后面的运算符重载中需要使用const?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40424999/

相关文章:

c++ - 多台机器运行相同的软件,有些无法连接到 firebird

c++ - 声明具有特定大小并插入元素的 vector<vector<pair<int, int>>?

c++ - 在 C++ 中自然禁止包装类

android - 显示从 Android 中的 native 代码获取的中间值

c++ - 如何修复 C++ 中的 PyImport_Import(python35.dll 中的异常)

c++ - 解决 Visual C++ 中缺少 vwscanf 的更好方法?

c++ - vector 复制构造函数 C++ : does it have to be linear time?

c++ - 英特尔 C++ 编译器 - const 字符串是可修改的

c++ - 在 Wireshark 中看到的数据报,Qt UDP 套接字未收到

c++ - 模板参数类型