我正在尝试在结构中重载这些运算符:
<
, <=
, ==
, >=
, >
, 可能稍后再重载!=
。
将结构的一个对象与同一结构的另一个对象进行比较似乎很容易,因为在为该场景重载运算符时,定义是自动对称的。
但是,如果我想将我的 structFOOD
与 a进行比较int
怎么办?这也很容易,只要FOOD
先出现,但是,int 先出现的场景呢?如果没有 g++ 给我这么多“必须只包含一个参数”错误,我该如何定义呢?
我意识到
bool operator> (const int &, const FOOD &) const;
由于“不止一个论点”的事情而出现问题。我明白了。
在我在互联网上搜索的所有论坛上,每个人的解决方案似乎都在使用friend
,但他们的困难总是在类的上下文中,而不是结构的上下文中。这是如何为 s 结构完成的?
struct FOOD {
int foodID;
double price;
bool operator> (const FOOD &) const; //FOOD > FOOD
bool operator>=(const FOOD &) const; //FOOD >= FOOD
bool operator==(const FOOD &) const; //FOOD == FOOD
bool operator<=(const FOOD &) const; //FOOD <= FOOD
bool operator< (const FOOD &) const; //FOOD < FOOD
bool operator> (const int &) const; //FOOD > int
bool operator>=(const int &) const; //FOOD >= int
bool operator==(const int &) const; //FOOD == int
bool operator<=(const int &) const; //FOOD <= int
bool operator< (const int &) const; //FOOD < int
bool operator> (const int &, const FOOD &) const; // int > FOOD
bool operator>=(const int &, const FOOD &) const; // int >= FOOD
bool operator==(const int &, const FOOD &) const; // int == FOOD
bool operator<=(const int &, const FOOD &) const; // int <= FOOD
bool operator< (const int &, const FOOD &) const; // int < FOOD
};
bool FOOD::operator> (const FOOD &f) const {return foodID > f.foodID;}//FOOD > FOOD
bool FOOD::operator>=(const FOOD &f) const {return foodID >= f.foodID;}//FOOD >= FOOD
bool FOOD::operator==(const FOOD &f) const {return foodID == f.foodID;}//FOOD == FOOD
bool FOOD::operator<=(const FOOD &f) const {return foodID <= f.foodID;}//FOOD <= FOOD
bool FOOD::operator< (const FOOD &f) const {return foodID < f.foodID;}//FOOD < FOOD
bool FOOD::operator> (const int &i) const {return foodID > i;} //FOOD > int
bool FOOD::operator>=(const int &i) const {return foodID >= i;} //FOOD >= int
bool FOOD::operator==(const int &i) const {return foodID == i;} //FOOD == int
bool FOOD::operator<=(const int &i) const {return foodID <= i;} //FOOD <= int
bool FOOD::operator< (const int &i) const {return foodID < i;} //FOOD < int
bool FOOD::operator> (const int &i, const FOOD &f) const {return i > f.foodID;}// int > FOOD
bool FOOD::operator>=(const int &i, const FOOD &f) const {return i >= f.foodID;}// int >= FOOD
bool FOOD::operator==(const int &i, const FOOD &f) const {return i == f.foodID;}// int == FOOD
bool FOOD::operator<=(const int &i, const FOOD &f) const {return i <= f.foodID;}// int <= FOOD
bool FOOD::operator< (const int &i, const FOOD &f) const {return i < f.foodID;}// int < FOOD
g++
给了我这些错误:
structsTransAndFood.cc:64:45: error: ‘bool FOOD::operator>(const int&, const FOOD&) const’ must take exactly one argument