- C++ 友元
- 前言
- 一、成员函数作为友元
- 二、类作为友元
- 三、全局函数作为友元
- 本文章如有错误,欢迎指正!
前言
当你想在类的成员函数外部直接访问对象的私有成员时,C++ 就提供了友元(friend)的概念。在类中指定的友元就可以访问该类中受保护的内容。
一、成员函数作为友元成员函数作为友元即为 类B 中的成员函数被 类A 视为友元,在这种情况下可以使用 类B 中被视为友元的函数访问 类A 中的受保护信息。
示例如下:
#include#include using namespace std; class A; class B{ public: B(); void find_name(); //必须是处于 public 下的成员函数才能做为友元 A *theA; private: void find_id(); //该成员函数处于 private 下所以无法作为友元 }; class A{ friend void B::find_name(); public: A(); private: string name; int id; }; A::A(){ name = "qwea"; id = 10; } B::B(){ theA = new A; } void B::find_name(){ cout << theA->name << endl; } void test(){ B theB; theB.find_name(); } int main() { test(); return 0; }
结果如下:
类作为友元即为 类B 将 类A 视为友元,在这种情况下,类A 中的方法都能访问 类B 中受保护元素。
代码如下(示例):
#include#include using namespace std; class B; class A{ public: A(); void find_name(); void find_id(); B *theB; }; class B{ friend class A; //将 类A 视为友元,使其内的方法能访问 类B 中受保护内容 public: B(); private: string name; int id; }; A::A(){ theB = new B; } B::B(){ name = "qaz"; id = 10; } void A::find_name(){ cout << theB->name << endl; } void A::find_id(){ cout << theB->id << endl; } void test(){ A theA; theA.find_name(); theA.find_id(); } int main(){ test(); return 0; }
结果如下:
全局函数作为友元即为 类A 将一个 全局函数 视为友元,在这种情况下,该全局函数能访问到 类A 中受保护内容。
代码如下(示例):
#include#include using namespace std; void find_NameAndId(); class A{ friend void find_NameAndId(A theA); public: A(); private: string name; int id; }; A::A(){ name = "tgh"; id = 10; } void find_NameAndId(A theA){ cout << theA.name << endl; cout << theA.id << endl; } int main(){ A theA; find_NameAndId(theA); return 0; }
结果如下:
本文章如有错误,欢迎指正!



