我知道朋友超负荷的运营商可以访问他们与朋友的私人成员,但是在访问其朋友的基类成员方面有什么规则?
我进行了一些测试,如下所示,发现派生类的朋友超载运算符可以访问基类的受保护成员。朋友功能不是不被视为与他们成为朋友的班级的一部分,为什么他们能够访问基类的受保护成员,就好像他们是派生类的成员函数一样?
#include <iostream>
#include <string>
using namespace std;
class Animal {
protected:
string name;
int age;
public:
Animal(string, int);
};
Animal::Animal (string n, int a) {
name = n;
age = a;
}
class Mouse : public Animal {
friend ostream& operator<< (ostream& out, const Mouse& obj);
private:
double tailLength;
double whiskersLength;
public:
Mouse(string, int, double, double);
};
Mouse::Mouse (string n, int a, double t, double w) : Animal(n, a) {
tailLength = t;
whiskersLength = w;
}
ostream& operator<< (ostream& out, const Mouse& obj) {
out << obj.name; //no error, why is this allowed?
return out;
}
int main() {
Mouse m1("nic", 2, 2.5, 3.5);
cout << m1 << endl;
cout << m1.name << endl; //error as expected
return 0;
}
这是因为基类Animal
的protected
成员name
在派生类Mouse
中可以访问,并且由于Overloaded operator<<
是派生类的CC_5,因此它将能够访问所有其成员。
但是在main()
函数中,您正在尝试访问基础外部和派生类的Animal
类的protected
成员,这是不允许的。