全局函数做友元
友元函数是使用friend关键字声明的函数,它可以访问相应类的保护成员和私有成员。
#include"iostream"
using namespace std;
#include<string>
class buiding{
friend void goodgay(buiding house);
public:
buiding() {
m_settingrom = "客厅";
m_bedrom = "卧室";
}
string m_settingrom;
private:
string m_bedrom;
};
void goodgay(buiding house) {
cout << "好朋友进入" << house.m_settingrom << endl;
cout << "好朋友进入" << house.m_bedrom << endl;
}
int main() {
buiding house;
goodgay(house);
return 0;
}
类做友元
友元类的使用friend关键字声明的类它的所有成员函数都是相应类的友元函数。
#include"iostream"
using namespace std;
#include<string>
class buiding{
friend class goodgay;
public:
buiding() {
m_settingrom = "客厅";
m_bedrom = "卧室";
}
string m_settingrom;
private:
string m_bedrom;
};
class goodgay {
public:
void visit() {
cout << "好朋友参观" << house.m_settingrom << endl;
cout << "好朋友参观" << house.m_bedrom << endl;
}
private:
buiding house;
};
int main() {
goodgay gg;
gg.visit();
return 0;
}
成员函数做友元
#include "iostream"
using namespace std;
#include "string"
class Building;
class goodGay
{
public:
goodGay();
void visit(); //只让visit函数作为Building的好朋友,可以发访问Building中私有内容
void visit2();
private:
Building *building;
};
class Building
{
//告诉编译器 goodGay类中的visit成员函数 是Building好朋友,可以访问私有内容
friend void goodGay::visit();
public:
Building();
public:
string m_SittingRoom; //客厅
private:
string m_BedRoom;//卧室
};
Building::Building()
{
this->m_SittingRoom = "客厅";
this->m_BedRoom = "卧室";
}
goodGay::goodGay()
{
building = new Building;
}
void goodGay::visit()
{
cout << "好基友正在访问" << building->m_SittingRoom << endl;
cout << "好基友正在访问" << building->m_BedRoom << endl;
}
void goodGay::visit2()
{
cout << "好基友正在访问" << building->m_SittingRoom << endl;
//cout << "好基友正在访问" << building->m_BedRoom << endl;
}
int main(){
goodGay gg;
gg.visit();
system("pause");
return 0;
}