【发布时间】: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 &),它将为您隐式转换为ItemStack。 -
您的代码不完整;特别是,它似乎缺少一个
main()函数和至少一个#include。请edit您的代码,这是您的问题的minimal reproducible example,然后我们可以尝试重现并解决它。您还应该阅读How to Ask。
标签: c++ operator-overloading compound-assignment