目录
一、基本概念
目的:让一个函数或者类,访问另一个类中的私有成员
关键字:friend
- 友元的三种实现
- 全局函数做友元
- 类做友元
- 成员函数做友元
二、全局函数做友元
代码示例
cpp
#include<iostream>
using namespace std;
class Building{
// 告诉编译器,goodgay全局变量是类Building 的好朋友,可以访问私有内容
friend void goodgay(Building * building);
public:
Building(){
keting = "客厅";
badroom = "卧室";
}
public:
string keting;
private:
string badroom;
};
void goodgay(Building * building){
cout<<"您的好友正在访问您的"<< " " <<building->keting<<endl;
cout<<"您的好友正在访问您的"<< " " <<building->badroom<<endl;
}
void test(){
Building b;
goodgay(&b);
}
int main(){
test();
}
三、类做友元
代码示例
cpp
#include<iostream>
using namespace std;
class Building;
class goodgay{
public:
goodgay();
void vis(); // 参观函数,访问Building中的属性
private:
Building * building;
};
class Building{
//告诉编译器,类goodgay是类Building 的好朋友,可以访问私有内容
friend class goodgay;
public:
Building();
public:
string keting;
private:
string badroom;
};
Building::Building(){ // 类外写成员函数
this->keting = "客厅";
this->badroom = "卧室";
}
goodgay::goodgay(){ // 类外写成员函数
building = new Building; //创建建筑物对象
}
void goodgay::vis(){
cout<<"您的好友正在访问您的"<<building->keting <<endl;
cout<<"您的好友正在访问您的"<<building->badroom <<endl;
}
void test(){
goodgay gg;
gg.vis();
}
int main(){
test();
}
四、成员函数做友元
代码示例
cpp
#include<iostream>
using namespace std;
class Building;
class goodgay{
public:
goodgay();
void vis();
void vis2();
private:
Building * building;
};
class Building{
//告诉编译器,类goodgay中的成员变量vis是类Building 的好朋友,可以访问私有内容
friend void goodgay::vis();
public:
Building();
public:
string keting;
private:
string badroom;
};
// 类外实现成员函数
Building::Building(){
this->keting = "客厅";
this->badroom = "卧室";
}
goodgay::goodgay(){
building = new Building;
}
void goodgay::vis(){
cout<<"您的好友vis正在访问您的"<<building->keting<<endl;
cout<<"您的好友vis正在访问您的"<<building->badroom<<endl;
}
void goodgay::vis2(){
cout<<"您的好友vis2正在访问您的"<<building->keting<<endl;
// cout<<"您的好友vis正在访问您的"<<building->badroom<<endl;
}
void test(){
goodgay gg;
gg.vis();
gg.vis2();
}
int main(){
test();
}