得到“不匹配'运算符+ =',没有已知的从参数1到'int'到'const ItemStack&'的转换

时间:2016-07-27 01:39:13

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

我一直很难找到重载+ =运算符的正确方法。我使用了似乎最流行的方法,但它似乎不符合这个程序的需要。如果有人可以帮助我解决这个编译错误或指向我正确的方向,这将是惊人的。这是代码。

问题功能......

////////////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;
 }

`

1 个答案:

答案 0 :(得分:2)

您的operator+=定义为

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

operator+=参数定义ItemStack &

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

items[loc] += q;

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