下面是代码
编码:
#include <iostream>
using namespace std;
class Rational {
int num; // numerator
int den; // denominator
friend istream& operator>> (istream & , Rational&);
friend ostream& operator<< (ostream & , const Rational&);
public:
Rational (int num = 0, int den = 1)
: num(num), den(den) {}
void getUserInput() {
cout << "num = ";
cin >> num;
cout << "den = ";
cin >> den;
}
Rational operator+(const Rational &);
};
Rational Rational::operator+ (const Rational& r) { //HERE
int n = num * r.den + den * r.num;
int d = den * r.den;
return Rational (n, d);
}
istream& operator>> (istream & is , Rational& r)
{
is >> r.num >> r.den;
}
ostream& operator<< (ostream & os , const Rational& r)
{
os << r.num << " / " << r.den << endl;;
}
int main() {
Rational r1, r2, r3;
cout << "Input r1:\n";
cin >> r1;
cout << "Input r2:\n";
cin >> r2;
r3 = r1 + r2;
cout << "r1 = " << r1;
cout << "r2 = " << r2;
cout << "r1 + r2 = " << r3;
return 0;
}
问题
上面的代码有一个 operator+ 重载,在 operator+ 定义中我们可以看到r
访问私有数据的参数(r.num 和 r.den)。为什么 C++ 允许参数访问类之外的私有数据?这是某种特殊情况吗?
谢谢你。