#ifndef _A_H_
#define _A_H_
#include<iostream>
using namespace std;
class A {
private:
int a;
public:
void show();
friend void display();//友元函数声明
};
#endif
#include "A.h"
void A::show() {
cout << "A::show()" << endl;
}
void display() {
//友元函数可以访问私有成员
A A1;
A1.a = 1;
cout << "friend display() a = " << A1.a << endl;
}
#include "A.h"
int main() {
A a1;
//a1.a = 1;错 普通函数不能访问私有成员
a1.show();
//a1.display();错 友元函数不是内成员函数
display();
return 0;
}
本文深入探讨了C++中友元函数的概念及其使用方法,通过具体实例展示友元函数如何访问类的私有成员,解释了普通函数与友元函数在访问权限上的区别。
1974

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



