因此,我是c ++的新手,并尝试创建具有操作重载的C ++分数类。一切都很好,直到我在主函数的小于比较行中收到错误为止:
Fraction someNum(15, 9);
......
if (someNum > 1)
cout << "15/9 > 1." << endl;
if (1 < someNum) //throws error
cout << "1 < someNum." << endl;
错误:
operator<(const error_condition& __lhs,
^~~~~~~~
c:\mingw\lib\gcc\mingw32\6.3.0\include\c++\system_error:274:3: note: no known conversion for argument 1 from 'int' to 'const std::error_condition&'
奇怪的是,大于比较的值可以正确打印输出,即使它们都是混合比较,也不会引发错误。
这是我其他.cpp文件中的相应代码:
//lesser than
bool Fraction::operator<(Fraction right) {
return (num * (denom * right.denominator())) < (right.numerator() * (denom * right.denominator()));}
//greater than
bool Fraction::operator>(Fraction right) {
return (num * (denom * right.denominator())) > (right.numerator() * (denom * right.denominator()));}
如您所见,除了所涉及的比较运算符外,代码行完全相同。但是,一个会引发错误,而一个不会。一旦拿走了最后的比较输出,一切都将正常工作。我根本不知道该如何解决...
任何指针将不胜感激。请让我知道是否需要更多信息。
谢谢!
答案 0 :(得分:2)
您将需要一个operator<
,它与显示的参数顺序匹配。您的示例中的op>
比较具有相反的参数顺序,因此它将匹配op>
重载,类似于您在代码中显示的op<
重载参数顺序。>
struct Foo {};
bool operator>(Foo, int);
struct Bar {};
bool operator>(Bar, int);
bool operator>(int, Bar); // This one has the parameters in both orders
int main() {
Foo f;
f > 1;
1 > f; // doesn't work
Bar b;
b > 1;
1 > b; // works
}
您还可以按如下方式将比较器放入结构中:
struct Bar {
friend bool operator>(Bar, int);
friend bool operator>(int, Bar);
};