C++(类做友元)

类做友元

  • 类做友元后可以访问另一个类的私有成员

示例:


#include <iostream>
#include <string>
using namespace std;

class Building;
class goodGay
{
public:
      goodGay();
      void visit();
private:
      Building *building;
};

class Building
{
      //告诉编译器goodGay类是building类的好朋友,可以访问到Building类中的私有内容
      friend class goodGay;
public:
      Building();
public:
      string m_SittingRoom; //客厅
private:
      string m_BedRoom; //卧室
};

Building::Building()
{
      this->m_SittingRoom="客厅";
      this->m_BedRoom="卧室";
}

void goodGay::visit()
{
	cout << "好基友正在访问" << building->m_SittingRoom << endl;
	cout << "好基友正在访问" << building->m_BedRoom << endl;

}

void test01()
{
      goodGay gg;
      gg.vist();
}

int main(void)
{
      test01();
      system("pause");
      return 0;
}
posted @ 2020-09-16 01:47  flyingswallow  阅读(218)  评论(0编辑  收藏  举报