C++学习(11)—— 友元
生活中你的家有客厅(Public),有你的卧室(Private)
客厅所有来的客人都可以过去,但是你的卧室是私有的,也就是说只有你能进去
但是呢,你也可以允许你的好闺蜜好基友进去
在程序里,有些私有属性也想让类外特殊的一些函数或类进行访问,就需要用到友元的技术
- 友元的目的就是让一个函数或者类访问另一个类中的私有成员
- 友元的关键字为 friend
友元的三种实现:
- 全局函数做友元
- 类做友元
- 成员函数做友元
1. 全局函数做友元
friend void goodGay(Building *building);
#include <iostream>
#include <string>
using namespace std;
class Building{
//告诉编译器goodGay全局函数是Building好朋友,可以访问Building中的私有成员
friend void goodGay(Building *building);
public:
Building(){
m_SittingRoom = "客厅";
m_BedRoom = "卧室";
}
string m_SittingRoom; //客厅
private:
string m_BedRoom; //卧室
};
//全局函数
void goodGay(Building *building){
cout << "好基友的全局函数 正在访问:" << building->m_SittingRoom << endl;
cout << "好基友的全局函数 正在访问:" << building->m_BedRoom << endl;
}
void test01(){
Building building;
goodGay(&building);
}
int main(){
test01();
return 0;
}
2. 类做友元
friend class GoodGay;
#include <iostream>
#include <string>
using namespace std;
class Building{
friend class GoodGay;
public:
Building();
string m_SittingRoom; //客厅
private:
string m_BedRoom; //卧室
};
class GoodGay{
public:
GoodGay();
void visit(); //参观函数,访问Building中的属性
Building *building;
};
//类外写成员函数
Building::Building(){
m_SittingRoom = "客厅";
m_BedRoom = "卧室";
}
GoodGay::GoodGay(){
//创建建筑物对象
building = new Building;
}
void GoodGay::visit(){
cout << "好基友正在访问:" << building->m_SittingRoom << endl;
cout << "好基友正在访问:" << building->m_BedRoom << endl;
}
void test01(){
GoodGay gg;
gg.visit();
}
int main(){
test01();
return 0;
}
3. 成员函数做友元
friend void GoodGay::visit();
#include <iostream>
#include <string>
using namespace std;
class Building;
class GoodGay{
public:
GoodGay();
void visit(); //让visit函数可以访问Building中私有成员
void visit2(); //让visit2函数不可以访问Building中私有成员
Building *building;
};
class Building{
friend void GoodGay::visit();
public:
Building();
string m_SittingRoom; //客厅
private:
string m_BedRoom; //卧室
};
//类外写成员函数
Building::Building(){
m_SittingRoom = "客厅";
m_BedRoom = "卧室";
}
GoodGay::GoodGay(){
//创建建筑物对象
building = new Building;
}
void GoodGay::visit(){
cout << "visit正在访问:" << building->m_SittingRoom << endl;
cout << "visit正在访问:" << building->m_BedRoom << endl;
}
void GoodGay::visit2(){
cout << "visit2正在访问:" << building->m_SittingRoom << endl;
//cout << "visit2正在访问:" << building->m_BedRoom << endl;
}
void test01(){
GoodGay gg;
gg.visit();
gg.visit2();
}
int main(){
test01();
return 0;
}
Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.