C++运算符 - 方法



这是我的代码:

struct Goods {
int amount;
int rarity;
Goods operator -(const goods &other);
};

这就是我尝试实现运算符方法的方式:

Goods Goods::operator -(const Goods &other) {
this->amount = amount - other.amount;
this->rarity = rarity - other.rarity;
}

但是此代码无法按预期工作。此测试的实际值

TEST(Mytest, GoodsMinus) {
Goods g1{3, 4};
Goods g2{2, 1};
ASSERT_EQ(1, (g1 - g2).amount);
ASSERT_EQ(3, (g1 - g2).rarity);
}

第一个断言的实际值是9435404,这显然是错误的。我在这里做错了什么?

您的方法没有返回任何内容,并且雪上加霜的是,它作为类似-=的方法运行,修改左侧操作数而不是返回新Good,同时保持输入不变(如果作为实例上的方法实现,这不是通常的方法,它应该是一个const方法(。

我强烈建议您阅读运算符重载的基本规则和习语是什么?,因为即使你修复了这些问题,你也会走上编写可维护的惯用代码的错误道路。

您的运算符 - 应该返回一个新对象,该对象存储计算的新值,在您的情况下,作为每个成员的差值。在您提供的代码中,您(语义上(实际上实现了运算符 -=,其中,您直接修改当前对象的数据;您实际上正在访问此>...数据,而不是新对象。

因此,您的 - 运算符应如下所示:

Goods Goods::operator-(const Goods &other) const {
Goods r;
r.amount = amount - other.amount;
r.rarity = rarity - other.rarity;
return r;
}

编辑: 正如我所建议的那样,我在运算符中添加了 const,这意味着您甚至可以使用 const 对象使用它(这是有道理的,因为您没有修改对象内部状态(

最新更新