友元

友元就是让非本类的函数能访问这个类的私有变量

友元的三种实现:

  1. 全局函数做友元
  2. 类做友元
  3. 成员函数做友元
  1 #include <iostream>
  2 #include <string>
  3 using namespace std;
  4 
  5 /*友元的关键字:friend
  6 友元的三种实现
  7 全局函数做友元
  8 类做友元
  9 成员函数做友元 
 10 */
 11 
 12 /*那么友元是什么呢
 13 我觉得就是让非本类的类或函数来访问本类的私有变量*/
 14 class GoodFriend; 
 15 class Building; 
 16 //class Building
 17 //{
 18 ////GGBond函数可以访问Building的私有变量 
 19 //friend void GGBond1(Building *building);
 20 //friend class GoodFriend;
 21 ////friend void GoodFriend::visit2();
 22 ////成员函数做友元没实现 
 23 //public:
 24 //    Building()
 25 //    {
 26 //        m_SittingRoom="客厅";
 27 //        m_BedRoom="卧室";
 28 //    }
 29 //public:
 30 //    string m_SittingRoom;//客厅
 31 //private:
 32 //    string m_BedRoom;//卧室 
 33 //
 34 //};
 35 
 36 
 37 class GoodFriend{
 38 public:
 39     void visit1();
 40 //    void visit2(){
 41 //        cout<<m_name<<"正在访问:"<<building->m_SittingRoom<<endl;
 42 //        cout<<m_name<<"正在访问:"<<building->m_BedRoom<<endl;
 43 //    }
 44 GoodFriend(string name);
 45 //    GoodFriend(string name){
 46 //    //创建建筑物对象
 47 //    building=new Building; 
 48 //    m_name=name;
 49 //}
 50     string m_name;
 51     Building *building;
 52 };
 53 
 54 class Building
 55 {
 56 //GGBond函数可以访问Building的私有变量 
 57 friend void GGBond1(Building *building);
 58 //friend class GoodFriend;
 59 friend void GoodFriend::visit1();
 60 //成员函数做友元没实现 
 61 public:
 62     Building()
 63     {
 64         m_SittingRoom="客厅";
 65         m_BedRoom="卧室";
 66     }
 67 public:
 68     string m_SittingRoom;//客厅
 69 private:
 70     string m_BedRoom;//卧室 
 71 
 72 };
 73 
 74 GoodFriend::GoodFriend(string name){
 75     //创建建筑物对象
 76     building=new Building; 
 77     m_name=name;
 78 }
 79 
 80 //类外定义函数 
 81 void GoodFriend::visit1(){
 82     cout<<m_name<<"正在访问:"<<building->m_SittingRoom<<endl;
 83     cout<<m_name<<"正在访问:"<<building->m_BedRoom<<endl;
 84 } 
 85 
 86 void test01(){
 87     GoodFriend gf("GGBond(goodFriend)");
 88     gf.visit1();
 89 }
 90 
 91 
 92 void GGBond1(Building *building){
 93     cout<<"GGBond1正在访问:"<<building->m_SittingRoom<<endl;
 94 //    //因为上面加了friend所有可以访问私有变量 
 95     cout<<"GGBond1正在访问:"<<building->m_BedRoom<<endl;
 96 }
 97 
 98 
 99 int main()
100 {
101      
102     Building b;
103     GGBond1(&b);
104     test01();
105     return 0;
106 }
友元

 

posted @ 2023-09-06 19:14  HuangWQ289  阅读(5)  评论(0编辑  收藏  举报