【问题标题】:Getting "no match for 'operator+=', no known conversion from argument 1 from 'int' to 'const ItemStack&' [closed]得到“'operator+='不匹配,没有从参数1从'int'到'const ItemStack&'的已知转换[关闭]
【发布时间】:2016-11-30 20:06:58
【问题描述】:

我一直很难找到重载 += 运算符的正确方法。我使用了似乎是最流行的方法,但它似乎不能满足该程序的需求。如果有人能帮我解决这个编译器错误或指出我正确的方向,那就太棒了。这是代码。

问题函数...

////////////storage.cpp
void storeItems( istream &inf, vector<ItemStack> &items ){
int id = 0; //temporary id
int q  = 0; //temporary count

cout << "Processing Log" << "\n";
printHorizontalLine( cout, '-', 36 );

while( inf >> id >> q ){
    int loc = sequentialSearch( items, id );

    if( loc != -1 ){
        items[loc] += q;   <------ This operator is causing the error.

        cout << "  Stored " 
             << right << setw(3) << q << " "
             << items[loc].getName()
             << "\n";
    }
    else{
        cout << "  Invalid ID (" << id << ")" << "\n"; 
    }
}
println();
}

///////////itemstack.cpp

ItemStack::ItemStack( int i, std::string n ){
id       = i;
name     = n;
quantity = 0;
}

/**
 *
 */
//void ItemStack::add( int amount ){
//    quantity += amount;
//}
inline
ItemStack& ItemStack::operator+= (const ItemStack &rhs) 
{
quantity+= rhs.quantity;
return *this;
}

inline
ItemStack operator+(ItemStack lhs, const ItemStack& rhs)
{
 lhs += rhs;
 return lhs;
}

/**
 *
 */
 bool ItemStack::lowSupply(){
// Note the similarity to a condition in an if statement
return (quantity < 10);
  }

 bool ItemStack::operator== (const ItemStack& s1) const
 {
     return id == s1.id
     && quantity == s1.quantity
     && name == s1.name;
 }

 bool ItemStack::operator< (const ItemStack& s1)
 {
     return id == s1.id;
 }

 inline
 ostream& operator<<( std::ostream &outs, const ItemStack &prt )
  {
     return outs;
 }

`

【问题讨论】:

  • 你的运营商很好,只是你的怎么用不对。
  • 那么,您预计items[loc] += q 会发生什么?您是否期望 q 隐式转换为 ItemStack 类型?还是别的什么?
  • 如果我将 += 定义为将 int 作为参数,我会得到对 'ItemStack::operator+=(int const&) 错误的未定义引用。我很难使用此重载运算符将不在类中的变量添加到已经是 int 的类变量中。
  • @Zivian 请显示您更新的失败代码。或者,向ItemStack 添加一个构造函数,将单个int 作为输入。然后您可以将int 传递给operator+=(const ItemStack &amp;),它将为您隐式转换为ItemStack
  • 您的代码不完整;特别是,它似乎缺少一个main() 函数和至少一个#include。请edit您的代码,这是您的问题的minimal reproducible example,然后我们可以尝试重现并解决它。您还应该阅读How to Ask

标签: c++ operator-overloading compound-assignment


【解决方案1】:

您的operator+= 定义为

ItemStack& ItemStack::operator+= (const ItemStack &rhs) 

operator+= 是为 ItemStack &amp; 参数定义的。

您正在尝试按如下方式使用它:

items[loc] += q;

qint,而不是 ItemStack。您的 += 运算符仅为 ItemStack 引用定义。

【讨论】:

  • 所以要将整数添加到项目堆栈的对象中,您会认为我只需将参数更改为 int 而不是 ItemStack 引用。但是,当我这样做时,我得到了一个未定义的参考错误。
  • 在不真正了解运算符重载的工作原理的情况下随机更改代码不太可能产生预期的结果。
猜你喜欢
  • 2022-07-29
  • 1970-01-01
  • 1970-01-01
  • 2018-06-25
  • 1970-01-01
  • 1970-01-01
  • 2020-06-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多