1

我有一个自定义课程。我们就叫它苹果吧。我这样重载加法运算符:

apple apple::operator+(const apple & other)
{
    return apple
    (
        this->x + other.x,
        this->y + other.y,
        this->z + other.z
    );
}

它工作得很好......直到我尝试添加两个 const 苹果。

const apple apple1;
const apple apple2;

auto apple3 = apple1 + apple2;

给我一个错误'没有运算符“+”匹配这些操作数操作数类型是:const apple + const apple'

添加 const 对象有什么技巧吗?

4

1 回答 1

6

您需要将加法运算符本身标记为const

apple apple::operator+(const apple & other) const;

运算符的当前形式不能保证它this不会被改变(即使它实际上并没有改变它),所以当加法的 LHS 是 a 时const apple,编译器不能使用它并抱怨没有合适的运算符可用。

请注意,通常的做法是通过定义一个自由函数operator+而不是成员来实现自定义加法,因为这样编译器可以使用构造函数将加法的 LHS 转换为如果需要 - 如果是成员函数apple,这是不可能的operator+.

于 2013-01-26T19:56:06.727 回答