#include <iostream>
using namespace std;
#include "fraction.h"
int main()
{
Fraction f(1,2);
Fraction g(1,2);
if (f > g) cout << f << " > " << g << endl;
return 0;
}
Fraction::Fraction()
{
//ctor
m_top = 0;
m_bottom = 1;
}
Fraction::Fraction(int t, int b)
{
//ctor
m_top = t;
m_bottom = b;
reduce();
}
bool Fraction operator>(const Fraction& l, const Fraction& r)
{
int a = l.getTop();
int b = l.getBottom();
int c = r.getTop();
int d = r.getBottom();
if ((a*d-c*b) > (b*d))
return true;
}
void Fraction::reduce()
{
int g=gcf(m_top, m_bottom);
m_top /= g;
m_bottom /= g;
}
/// recursive
int Fraction::gcf(int m, int n)
{
if (n == 0) return m;
return gcf(n, m % n);
}
#ifndef FRACTION_H
#define FRACTION_H
#include <iostream>
using namespace std;
class Fraction
{
public:
Fraction();
Fraction(int, int);
int getTop() {return m_top;}
int getBottom() {return m_bottom;}
void set(int t, int b) {m_top=t; m_bottom=b; reduce();}
Fraction( Fraction t, Fraction b);
protected:
private:
void reduce();
int gcf(int, int);
int m_top;
int m_bottom;
};
ostream& operator<<(ostream&, Fraction);
Fraction operator+(Fraction l, Fraction r);
Fraction operator*(Fraction l, Fraction r);
Fraction operator/(Fraction l, Fraction r);
Fraction operator>(Fraction l, Fraction r);
Fraction operator>=(Fraction l, Fraction r);
Fraction operator<(Fraction l, Fraction r);
Fraction operator<=(Fraction l, Fraction r);
Fraction operator==(Fraction l, Fraction r);
Fraction operator!=(Fraction l, Fraction r);
#endif // FRACTION_H
日志说int main()发生错误 错误:无法转换&#39;运算符&gt;(f,g)&#39;来自&#39;分数&#39;到了布尔&#39;
有人可以告诉我我做错了什么,并修复我的代码? bool语句有问题吗?如果是这样我该怎么办?
答案 0 :(得分:1)
Fraction operator>(Fraction l, Fraction r);
Fraction operator>=(Fraction l, Fraction r);
Fraction operator<(Fraction l, Fraction r);
Fraction operator<=(Fraction l, Fraction r);
Fraction operator==(Fraction l, Fraction r);
Fraction operator!=(Fraction l, Fraction r);
这些运算符应返回布尔值,而不是Fraction
:
bool operator>(Fraction l, Fraction r);
bool operator>=(Fraction l, Fraction r);
bool operator<(Fraction l, Fraction r);
bool operator<=(Fraction l, Fraction r);
bool operator==(Fraction l, Fraction r);
bool operator!=(Fraction l, Fraction r);
编译器告诉您无法将返回值Fraction
转换为bool
,因为这些操作符需要它。
修改强>
此外,这些运营商的预期签名是:
bool operator>(const Fraction& l, const Fraction& r);
bool operator>=(const Fraction& l, const Fraction& r);
bool operator<(const Fraction& l, const Fraction& r);
bool operator<=(const Fraction& l, const Fraction& r);
bool operator==(const Fraction& l, const Fraction& r);
bool operator!=(const Fraction& l, const Fraction& r);
const
因为这些操作符不应修改输入值,并且引用 &
是为了避免复制整个对象。