有些私有属性,可需要让类外特殊的一些函数或类进行访问,就需要利用友元。
友元的关键字为fiend
友元的三种实现方法
一、全局函数作友元
将全局函数的声明写在类的定义内,并在前面添加关键字friend。
例:friend void func(Person *person);
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 
 | class Person{
 friend void goodFriend(Person *person);
 public:
 Person(){
 m_Name = "Huffie";
 m_Money = 0;
 }
 public:
 string m_Name;
 
 private:
 double m_Money;
 };
 
 void goodFriend(Person *person){
 cout << "Friends is getting:" << person->m_Name << endl;
 cout << "Friends is getting:" << person->m_Money << endl;
 }
 
 
 | 
二、类作友元
语法:friend class className;
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 
 | #include<iostream>#include<string>
 using namespace std;
 
 
 
 class Person{
 friend class goodFriend;
 public:
 Person();
 
 public:
 string m_Name;
 private:
 double m_Money;
 };
 
 Person::Person(){
 m_Name = "Huffie";
 m_Money = 100;
 }
 
 
 class goodFriend{
 public:
 goodFriend();
 
 void get();
 
 Person * person;
 };
 
 goodFriend::goodFriend(){
 person = new Person;
 }
 
 void goodFriend::get(){
 cout << "goodFriend类正在访问:" << person->m_Name << endl;
 cout << "goodFriend类正在访问:" << person->m_Money << endl;
 }
 
 
 void test01(){
 goodFriend gf;
 gf.get();
 }
 
 int main(){
 
 test01();
 
 system("pause");
 return 0;
 }
 
 | 
三、成员函数作友元
例:friend void className::func();
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 
 | #include<iostream>#include<string>
 using namespace std;
 
 class Person;
 
 class goodFriend{
 public:
 goodFriend();
 
 void get1();
 void get2();
 
 Person * person;
 
 };
 
 class Person{
 friend void goodFriend::get1();
 public:
 Person();
 string m_Name;
 private:
 double m_Money;
 };
 
 Person::Person(){
 m_Name = "Huffie";
 m_Money = 100;
 }
 
 goodFriend::goodFriend(){
 person = new Person;
 }
 
 void goodFriend::get1(){
 cout << "get函数正在访问:" << person->m_Name << endl;
 cout << "get函数正在访问:" << person->m_Money << endl;
 }
 
 void goodFriend::get2(){
 cout << "get函数正在访问:" << person->m_Name << endl;
 
 }
 
 void test(){
 goodFriend gf;
 gf.get1();
 gf.get2();
 }
 
 int main(){
 
 test();
 
 system("pause");
 return 0;
 }
 
 | 
参考:黑马程序员匠心之作|C++教程从0到1入门编程,学习编程不再难
链接:https://www.bilibili.com/video/BV1et411b73Z