#include<stdlib.h>
#include<iostream>
#include<string>
using namespace std;
/*
4.4.2 类做友元
*/
class Building; // 声明Building类,后续会写,防止Goodgay类中引用时报错
class Goodgay{
public:
void visit();
Goodgay(); // 构造函数
private:
Building * building;
};
class Building{
//告诉编译器 goodGay类是Building类的好朋友,可以访问到Building类中私有内容
friend class Goodgay;
public:
string setting_room;
private:
string bed_room;
public:
Building(); // 构造函数声明
};
Goodgay::Goodgay(){
building = new Building; // 在堆区创建对象
}
void Goodgay::visit(){
cout << "朋友类正在访问:" << building->setting_room << endl;
cout << "朋友类正在访问:" << building->bed_room << endl; // 正常无法访问,会报错;声明友元后可访问
}
Building::Building(){ // 类外写成员函数,实现构造函数,注意需要在函数名前加作用域
// 初始化赋值
setting_room = "客厅";
bed_room = "卧室";
}
void test1(){
Goodgay gg;
gg.visit();
}
int main()
{
test1();
system("pause");
return 0;
}
11.4.2重学C++之【类做友元】
猜你喜欢
转载自blog.csdn.net/HAIFEI666/article/details/114881600
今日推荐
周排行