语法:
    friend class 类名;

    1. //类做友元
    2. class Building;
    3. class GoodGay
    4. {
    5. public:
    6. GoodGay();
    7. void visit(); //参观函数 访问Building中的属性
    8. Building* building;
    9. };
    10. class Building
    11. {
    12. //GoodGay类是本类的好朋友 可以访问本类的私有成员
    13. friend class GoodGay;
    14. public:
    15. Building();
    16. public:
    17. string m_SittingRoom; //客厅
    18. private:
    19. string m_BedRoom; //卧室
    20. };
    21. //类外写成员函数
    22. Building::Building()
    23. {
    24. m_SittingRoom = "客厅";
    25. m_BedRoom = "卧室";
    26. }
    27. GoodGay::GoodGay()
    28. {
    29. //创建建筑物对象
    30. building = new Building;
    31. }
    32. void GoodGay::visit()
    33. {
    34. cout << "好朋友类正在访问:" << building->m_SittingRoom << endl;
    35. cout << "好朋友类正在访问:" << building->m_BedRoom << endl;
    36. }
    37. void test01()
    38. {
    39. GoodGay gg;
    40. gg.visit();
    41. }
    42. int main()
    43. {
    44. test01();
    45. system("pause");
    46. return 0;
    47. }