我有代表卡片组的 Pile 类,因此包含 Card 类的实例。 我重载了两个运算符,Pile::operator+= 和 Pile::operator--。
int main()
{
Pile pile1(false); //construct an empty pile/deck
Pile pile2(true); //construct a full deck with all 52 cards
output(pile1,pile2); //just a little procedure to print both decks
pile1 += --pile2;
output(pile1,pile2);
...
运算符 += 以另一个 Pile 作为引用,并将参数 Pile 中的每张牌移动到 *this。 运算符(operator) -- 从牌堆中取出最上面的牌,并返回包含该牌的牌堆。
g++ 给我的是一个编译时错误说明
error: no match for 'operator+=' in 'pile1 += Pile::operator--()()'
note: candidate is: void Pile::operator+=(Pile&)
下面是重载运算符:
void Pile::operator+=(Pile &other)
{
Node *n = other.listHead;
//add each card from other to *this
while((n = n->getNext()) != NULL)
{
this->newCardToList(other.drawCard());
}
}
Pile Pile::operator--()
{
Pile pile(false);
pile.newCardToList(this->drawCard());
return pile;
}
在我看来,operator+= 试图将 -- 作为参数。 我试过 pile1 += (--pile2);但这并没有改变任何东西。
我想要(或需要在这里做)的事情是从 pile2 中取出最上面的卡片 并将其放入pile1。你能指出这里出了什么问题吗,因为我什么都想不出来?
编辑: += 需要在此处修改两个对象。这是必需的,因为在我们的类(class)中给我们这个练习项目的人要求我们这样做。不过他的设计真的很糟糕,所以如果这个解决方案根本不可能,我也不会感到惊讶。
最佳答案
operator+=
的签名和行为是错误的。算术运算符按值工作,您的重载也应该如此。具有变异的 +=
肯定是运算符重载被滥用的情况之一。
根据描述,这里发生的是对象标识和值标识的混淆。与将某种类型的对象从一个存储空间移动到另一个存储空间不同,从值的角度思考通常更容易、更好地实现并且在 C++ 等语言中更自然。
关于c++ - 重载运算符试图将另一个重载运算符作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8368602/