- 全局函数作为友元函数
- friend 类型 函数名(类名* 变量名);
- 类作为友元类
- friend class 类名;
- 类中的成员函数作为友元函数
- friend void 类名::类中函数名();
#include<iostream>
#include<string>
using namespace std;
class building;
class room {
private:
int rid;
int num;
building *d;
public:
room(int rid, int num);
void getAllInfo();
};
class building {
//friend class room;
friend void room::getAllInfo();
friend void test(building* b1);
private:
string name;
string position;
int rooms;
int storeys;
public:
building() {
this->name = "abc";
this->position="def";
this->rooms=21;
this->storeys =12;
}
building(string name,string position,int rooms,int storeys)
:name(name),position(position),rooms(rooms),storeys(storeys) {
}
void getInfo() {
cout<<"name: " << this->name << endl;
cout << "position: " << this->position << endl;
cout << "rooms: " << this->rooms << endl;
cout << "storeys: " << this->storeys << endl;
}
};
room::room(int rid, int num) {
this->rid = rid;
this->num = num;
this->d = new building;
}
void room::getAllInfo() {
cout << this->d->name << endl;
}
void test(building *b1) {
building* b = new building("asdasd","asdqwd",12,21);
b->getInfo();
room* r = new room(1,2);
r->getAllInfo();
cout<<b1->name << endl;
}
int main() {
building b1("asdasd", "asdqwd", 12, 21);
test(&b1);
system("pause");
return EXIT_SUCCESS;
}