1.类作为友元,以及相关代码案例
#include<iostream>
using namespace std;#include<string>//类做友元
class Building;
class GoodGay {
public:GoodGay();void visit();//参观函数 访问Building中的属性Building* building;
};class Building {//加了friend说明GoodGay类是本类的好朋友,可以访问本类的私有成员。friend class GoodGay;
public:Building();public:string livingRoom;//客厅private:string BedRoom;//卧室};//类外写成员函数Building::Building() {livingRoom = "客厅";BedRoom = "卧室";
}GoodGay::GoodGay() {//创建建筑物对象building = new Building;
}void GoodGay::visit() {cout << "好朋友的类正在访问:" << building->livingRoom << endl;//cout << "好朋友的类正在访问:" << building->BedRoom << endl;//此时会报错,因为是私有属性cout << "好朋友的类正在访问:" << building->BedRoom << endl;//加了friend就不会报错了}void test01() {GoodGay Gg;Gg.visit();
}int main() {test01();system("pause");return 0;
}
关键代码:
代码执行结果: