C++過載操作符之二(輸入>>,輸出
阿新 • • 發佈:2018-12-23
#include<iostream> using namespace std; class Rational { private: int numerator; int denominator; public: Rational(int n, int d) :numerator(n), denominator(d){} //乘法操作符既可以使用成員過載又可以使用友元過載的 /* friend Rational operator *(const Rational &l, const Rational &r) { return Rational((l.numerator*r.numerator) , (l.denominator*r.denominator)); } */ const Rational operator *(const Rational &r) { return Rational((this->numerator*r.numerator), (this->denominator*r.denominator)); } //輸入輸出的操作符只能使用友元過載 friend ostream & operator<<(ostream &o, Rational & r) { o << r.numerator << "/" << r.denominator << endl; return o; } //修改了物件r,故用const修飾是錯誤的,會導致過載失敗 /* friend istream & operator>>(istream &i, const Rational & r) { char c; i >> r.numerator >> c >> r.denominator; return i; } */ friend istream &operator>>(istream &i, Rational &r) { char c; i >> r.numerator >> c >> r.denominator; return i; } }; int main() { Rational r1(1, 2); Rational r2(3, 5); Rational res = r1*r2; cout << "r1:" << r1 << "r2:" << r2; cout << "r1*r2=" << res << endl; cin >> r1 >> r2; cout << "r1:" << r1 << "r2:" << r2; res = r1*r2; cout << res << endl; return 0; }