操作符重载中的类数据封装(私有数据) [英] Class Data Encapsulation(private data) in operator overloading
问题描述
以下是代码
代码:
#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 ++允许参数访问类外的私有数据?
The above code has a operator+ overloading , in the operator+ definition we can see the parameter r
accessing the private data (r.num and r.den) . Why C++ allow the parameter to access private data outside of the class ? Is it some kind of a special case?
谢谢。
推荐答案
p>访问指定符适用于类级别,而不是实例,因此 Rational
类可以查看任何其他 Rational $ c> $ c> instance。由于你的
Rational运算符+
是一个成员函数,它可以访问它的 Rational
参数的私有数据。
Access specifiers apply at the level of classes, not instances, so the Rational
class can see private data members of any other Rational
instance. Since your Rational operator+
is a member function, it has access to private data of it's Rational
argument.
注意:规范方法是定义一个成员 operator + =
,然后使用它来实现非成员 operator +
Note: the canonical approach is to define a member operator +=
, and then use that to implement a non-member operator+
struct Foo
{
int i;
Foo& operator+=(const Foo& rhs)
{
i += rhs.i;
return *this;
}
};
Foo operator+(Foo lhs, const Foo& rhs)
{
return lhs += rhs;
}
这篇关于操作符重载中的类数据封装(私有数据)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!