友元的目的
让一个类或函数去访问另一个类中的私有成员
关键字
friend
分类:
全局函数做友元
类友元
成员函数做友元
1.全局函数做友元
class Bulid {
friend void run();//设置友元
public:
Bulid();
string setingroom;
private:
string bedroom;
};
//类外实现成员函数
Bulid::Bulid(){
this->setingroom = "客厅";
this->bedroom = "卧室";
}
void run() {
Bulid bulid;
cout << "好基友正在访问" << bulid.setingroom << endl;
cout << "好基友正在访问" << bulid.bedroom << endl;
}
int main() {
run();
}
可以看到run函数做友元后可以访问私有变量 bedroom
2.类友元
class gayfriend {
private:
Bulid * bulid;//Bulid类的指针
public :
gayfriend();//构造函数
public:
void vist();
};
class Bulid {
friend class gayfriend;//设置类友元
public:
Bulid();//构造函数
string setingroom;
private:
string bedroom;
};
//设置类外成员函数
Bulid::Bulid(){
this->setingroom = "客厅";
this->bedroom = "卧室";
}
gayfriend::gayfriend() {
this->bulid = new Bulid;//此处不释放内存了,重点不在这
}
void gayfriend::vist() {
cout << "好基友拜访了" << bulid->setingroom<<endl;//输出正常
cout << "好基友拜访了" << bulid->bedroom<<endl;//已经设置友元,输出正常
}
void run() {
gayfriend gay;
gay.vist();
}
int main(){
run();
}
3.成员函数做友元
class Bulid;
class gayfriend {
private:
Bulid* bulid;
public:
gayfriend();
void vist();
};
class Bulid {
friend void gayfriend::vist();//设置成员函数为友元 注意gayfriend类的代码需在Bulid之前,不然编译器不会识别
public:
Bulid();//构造函数
string setingroom;
private:
string bedroom;
};
//类外实现成员函数
Bulid::Bulid(){
this->setingroom = "客厅";
this->bedroom = "卧室";
}
gayfriend::gayfriend() {
bulid = new Bulid;
}
void gayfriend::vist() {
cout << "基友访问了" << bulid->setingroom << endl;//访问客厅
cout << "基友访问了" << bulid->bedroom << endl;//访问私有卧室,成功
}
void run() {
gayfriend gay;
gay.vist();
}
int main(){
run();
}