c-运算符重载中的类数据封装(私有数据)
作者:互联网
下面是代码
编码:
#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;
}
问题
上面的代码有一个运算符重载,在运算符定义中我们可以看到参数r访问私有数据(r.num和r.den).为什么C允许参数访问类外部的私有数据?这是一种特殊情况吗?
谢谢.
解决方法:
访问说明符适用于类级别,而不是实例级别,因此Rational类可以查看任何其他Rational实例的私有数据成员.由于您的Rational运算符是成员函数,因此可以访问其Rational参数的私有数据.
注意:规范方法是定义一个成员运算符=,然后使用它来实现一个非成员运算符
struct Foo
{
int i;
Foo& operator+=(const Foo& rhs)
{
i += rhs.i;
return *this;
}
};
Foo operator+(Foo lhs, const Foo& rhs)
{
return lhs += rhs;
}
标签:c,operator-overloading,encapsulation 来源: https://codeday.me/bug/20191013/1906528.html