子类友元可以使用父类protected成员
- 样例
#include<iostream>
using namespace std;
class A
{
public:
A(int temp=1):a(temp){
}
protected:
int a;
};
class B:public A
{
friend void print(B b);
};
void print(B b)
{
cout<<b.a<<endl;
}
int main()
{
B b;
print(b);
return 0;
}
- 运行

子类友元不可以使用父类private成员
- 样例
#include<iostream>
using namespace std;
class A
{
public:
A(int temp=1):a(temp){
}
private://修改的地方
int a;
};
class B:public A
{
friend void print(B b);
};
void print(B b)
{
cout<<b.a<<endl;
}
int main()
{
B b;
print(b);
return 0;
}
- 运行

结论
子类友元可以使用父类protected成员
子类友元不可以使用父类private成员
文章讨论了C++中子类友元的权限限制,指出友元函数可以访问父类的protected成员,但不能访问private成员。通过两个示例展示了这一规则的应用。
1074

被折叠的 条评论
为什么被折叠?



