目录
简介
在程序里有些私有属性,想让类外特殊的一些函数或者类进行访问可以采用友元技术。友元的目的就是让一个函数或者类访问另一个类的私有成员
友元的三种实现
1.全局函数做友元
#include<iostream>
using namespace std;
class Home {
friend void visit(Home* home);
public:
Home() {
this->sittingroom = "客厅";
this->bedroom = "卧室";
}
string sittingroom;
private:
string bedroom;
};
void visit(Home* home) {
cout << "访问" << home->bedroom << endl;
cout << "访问" << home->sittingroom << endl;
}
int main()
{
Home home;
visit(&home);
return 0;
}
2.类做友元
#include<iostream>
using namespace std;
class goodfriend;
class Home {
friend goodfriend;
public:
Home() {
this->sittingroom = "客厅";
this->bedroom = "卧室";
}
string sittingroom;
private:
string bedroom;
};
class goodfriend {
public:
goodfriend() {
home = new Home();
}
void visit() {
cout << "访问" << home->bedroom << endl;
cout << "访问" << home->sittingroom << endl;
}
private:Home* home;
};
int main()
{
goodfriend gf;
gf.visit();
return 0;
}
3.成员函数做友元
#include<iostream>
using namespace std;
class Home;
class goodfriend {
public:
goodfriend();
void visit();
private:Home* home;
};
class Home {
friend void goodfriend::visit();
public:
Home() {
this->sittingroom = "客厅";
this->bedroom = "卧室";
}
string sittingroom;
private:
string bedroom;
};
goodfriend::goodfriend() {
home = new Home();
}
void goodfriend::visit() {
cout << "访问" << home->bedroom << endl;
cout << "访问" << home->sittingroom << endl;
}
int main()
{
goodfriend gf;
gf.visit();
return 0;
}