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