友元函数怎么不管用了
我想写输入输出流>>,<<的重载函数运算符
类定义如下:
#ifndef RATIONAL_H
#define RATIONAL_H
#include <iostream>
using namespace std;
class Rational{
public:
Rational();
Rational(long numerator, long denominator);
long getNumerator();
long getDenominator();
Rational add(Rational &secondRational);
Rational subtract(Rational &secondRational);
Rational multiply(Rational &secondRational);
Rational divide(Rational &secondRational);
int compareTo(Rational &secondRational);
bool equals(Rational &secondRational);
int intValue();
double doubleValue();
string toString();
// Define function operators for relational operators
bool operator<(Rational &secondRational);
bool operator<=(Rational &secondRational);
bool operator>(Rational &secondRational);
bool operator>=(Rational &secondRational);
bool operator!=(Rational &secondRational);
bool operator==(Rational &secondRational);
// Define function operators for arithmetic operators
Rational operator+(Rational &secondRational);
Rational operator-(Rational &secondRational);
Rational operator*(Rational &secnodRational);
Rational operator/(Rational &secondRational);
// Define function operators for shorthand operators
Rational operator+=(Rational &secondRational);
Rational operator-=(Rational &secondRational);
Rational operator*=(Rational &secondRational);
Rational operator/=(Rational &secondRational);
// Define fucntion operator[]
long& operator[](const int &index);
// Define function operators for prefix++ and --
Rational operator++();
Rational operator--();
// Define function operators for postfix ++ and --
Rational operator++(int dummy);
Rational operator--(int dummy);
// Define function operators for unary + and -
Rational operator+();
Rational operator-();
// Define the output and input operator
friend ostream &operator<<(ostream &stream, Rational &rational); // 重载输出流的友元函数
friend istream &operator>>(istream &stream, Rational &rational); // 重载输入流的友元函数
// Define function operator for conversion
operator double();
private:
long numerator;
long denominator;
static long gcd(long n, long d);
};
#endif
// Define the output and input operator
ostream &operator<<(ostream &str, const Rational &rational){
str << rational.numerator << " / " << rational.denominator; // 编译的时候显示这里不能获取private 成员
return str;
}
istream &operator>>(istream &str, Rational &rational){
cout << "Enter numerator: ";
str >> rational.numerator;
cout << "Enter denominator: ";
str >> rational[1];
return str;
}
friend ostream &operator<<(ostream &stream, Rational &rational);//这是声明
ostream &operator<<(ostream &str, const Rational &rational){//这是定义
str << rational.numerator << " / " << rational.denominator;
return str;
}