c++中运算符重载的基本用法
要求使用以下类的声明,来测试运算符重载。
class rational
{
public:
//构造函数
rational(int num,int denom);
//重载比较操作符
bool operator<(rational r) const;
bool operator>(rational r) const;
bool operator==(rational r) const;
private:
//定义一个有理数num为分母,den为分子
long num,den;
};
话不多说,直接上代码!!!
#includeusing namespace std; class rational{ public: //构造函数 rational(int num, int denom) {}; //重载比较操作符 bool operator<(rational r) const; bool operator>(rational r) const; bool operator==(rational r) const; private: //定义一个有理数num为分母,den为分子 long num, den; }; bool rational::operator<(rational r)const { if (r.den / r.num < den / num) return 1; else return 0; } bool rational::operator>(rational r)const { if (r.den / r.num > den / num) return 1; else return 0; } bool rational::operator==(rational r)const { if (r.den / r.num == den / num) return 1; else return 0; } int main() { int w; rational a(3,4); rational b(4, 4); rational c(4,5); rational d(4, 5); w = (a > b); if (a > b) cout << "a>b" << " " << w << endl; else cout << "等式不成立" << endl; w = (c == d); if (c == d) cout << "c=d" << " " << w << endl; else cout << "等式不成立" << endl; }



