友元函数: 不是类成员函数, 是一个类外的函数, 但是可以访问类所有成员.
- class Point{
- public:
- friend void fun(Point t);// 友元函数
- private:
- int a;
- protected:
- int b;
- };
- void fun(Point t)
- {
- t.a = 100;
- t.b = 2000;
- cout <<t.a << " " << t.b << endl;
- }
- int main()
- {
- Point test;
- fun(test);
- system("pause");
- return 0;
- }
运行结果:
友元类: 类 A 是类 B 的友元类, 则 A 就可以访问 B 的所有成员(成员函数, 数据成员).(类 A, 类 B 无继承关系)
- class Point{
- friend class Line;
- public:
- void fun()
- {
- this->x = 100;
- this->y = 120;
- }
- private:
- int x;
- protected:
- int y;
- };
- class Line{
- public:
- void printXY()
- {
- t.fun();
- cout <<t.x << " " << t.y << endl;
- }
- private:
- Point t;
- };
- int main()
- {
- Line test;
- test.printXY();
- system("pause");
- return 0;
- }
运行结果:
友成员函数: 使类 B 中的成员函数成为类 A 的友元函数, 这样类 B 的该成员函数就可以访问类 A 的所有成员 (成员函数, 数据成员) 了
- class Point;// 在此必须对 Point 进行声明, 如不声明将会导致第 5 行(void fun(Point t);)"Point" 报错(无法识别的标识符)
- class Line{
- public:
- void fun(Point t);
- //void Line::fun(Point t)// 在此编译器无法获知 class Point 中到底有哪些成员, 所以应在 Point 后面定义
- //{
- // t.x = 120;
- // t.y = 130;
- // t.print();
- //}
- };
- class Point{
- public:
- friend void Line::fun(Point t);
- Point(){}
- void print()
- {
- cout << this->x <<endl;
- cout << this->y << endl;
- }
- private:
- int x;
- protected:
- int y;
- };
- void Line::fun(Point t)// 应在此定义 fun 函数
- {
- t.x = 120;
- t.y = 130;
- t.print();
- }
- int main()
- {
- Point test;
- Line LL;
- LL.fun(test);
- system("pause");
- return 0;
- }
运行结果:
总结: 关键字 "friend" 描述的函数就是友元函数,"friend" 所在类的所有成员都可被友元函数访问.(带有关键字 "friend" 的类, 就说明这个类有一个好朋友, 他的好朋友就是关键字 "friend" 后面跟的那个函数或类. 他的好朋友可以访问他的所有成员 )
来源: http://www.bubuko.com/infodetail-2989589.html