今天,我刚刚学习了有关在C ++中重载运算符的知识。特别是I / O运算符和算术运算符。我试图通过编写这样的代码将两者结合起来
cout << a + b; // both a and b are 2 objects belonging to the same class called Fraction.
但是,我无法使其达到预期的效果。您可以在下面的代码中看到它。
#include <iostream>
using namespace std;
class Fraction
{
public:
int numerator, denominator;
friend istream& operator >> (istream&, Fraction&);
friend ostream& operator << (ostream&, Fraction&);
Fraction operator + (Fraction x)
{
Fraction tmp;
tmp.denominator = denominator * x.denominator;
tmp.numerator = numerator * x.denominator + x.numerator*denominator;
return tmp;
}
};
istream& operator >> (istream& is, Fraction &x)
{
is >> x.numerator >> x.denominator;
return is;
}
ostream& operator << (ostream& os, Fraction &x)
{
os << x.numerator << "/" << x.denominator << " ";
return os;
}
int main()
{
Fraction a, b;
cin >> a >> b;
Fraction c = a + b;
cout << c; // This code worked but required an extra object to be declared.
// cout << a + b; Compiler error. How to make the "<<" operator to print the result as intended
return 0;
}