内容纲要
118讲 友元-全局函数做友元、友元类、成员函数做友元
全局函数做友元
- 友元打穿了访问权限,让特殊的函数或者成员能访问到私有属性。
//goodGay 全局函数是 Building的好基友,能访问,。让我访问。(打穿私有成员权限)
friend void goodGay(Building* building);
#include<iostream>
#include"string"
using namespace std;
class Building
{
//goodGay 全局函数是 Building的好基友,能访问,。让我访问。(打穿私有成员权限)
friend void goodGay(Building* building);
public:
Building() {
m_SettingRoom = "客厅";
m_BedRoom = "卧室";
}
public:
string m_SettingRoom; //定义客厅
private:
string m_BedRoom;//定义卧室
};
void goodGay(Building *building) {
cout << "好基友的全局函数正在访问: " << building->m_SettingRoom << endl;
cout << "好基友的全局函数正在访问: " << building->m_BedRoom << endl;
}
void test() {
Building building;
goodGay(&building);
}
void main() {
test();
}
类做友元(友元类)
作用:一个类访问另外一个类的私有成员。
tip:在写类的时候,可以先声明,让编译器知道你会有这个类,不让编译器报错。
#include<iostream>
#include"string"
using namespace std;
//类做成员
class Building;
class GoodGay {
public:
GoodGay();
public:
void visit();
Building * buildingl;
};
class Building {
friend void GoodGay::visit();
public:
Building(); //可以在类外写成员函数。
public:
string m_SettingRoom;
private:
string m_BedRoom;
};
void GoodGay::visit() {
cout << "好基友正在访问: " << buildingl->m_SettingRoom << endl;
cout << "好基友正在访问: " << buildingl->m_BedRoom << endl; //可以访问私有属性
}
GoodGay::GoodGay() {
buildingl = new Building;
}
Building::Building() { //在类外写Building 类中的成员函数。。。也有这个方法。
m_SettingRoom = "客厅";
m_BedRoom = "卧室";
}
void test() {
GoodGay goodgay;
goodgay.visit();
}
void main() {
test();
}
成员函数做友元
#include<iostream>
#include"string"
using namespace std;
class Building;
class GoodGay {
public:
GoodGay();
Building * building;
void visit();//让visit() 函数可以访问Building 的成员
void visit2();
};
class Building {
friend void GoodGay::visit2();
public:
Building();
public:
string m_SettingRoom;
private :
string m_BeddingRoom;
};
GoodGay::GoodGay() {
building = new Building;
}
Building::Building() {
m_SettingRoom = "客厅";
m_BeddingRoom = "卧室";
}
void GoodGay::visit() {
cout << "visit()正在访问Building的公有属性:" << building->m_SettingRoom << endl;
//cout << "visit()正在访问Building的私有属性:" << building->m_BeddingRoom << endl;//报错,不可访问
}
void GoodGay::visit2() {
cout << "visit2()友元成员正在访问Building的私有属性:" << building->m_BeddingRoom << endl;
}
void test() {
GoodGay goodGay;
goodGay.visit();
goodGay.visit2();
}
void main() {
test();
}