C++中,有些类的私有属性有时候也想让类外的一些函数或者类可以访问,这个时候就需要用到友元的技术。
友元的目的是想让一个函数或者类访问另一个类中的私有成员。
关键字:friend
实现方式:
1.成员函数做友元
class Father;
class Son{
public:
Son();
// 只让visit1()做Father的友元,可以访问Father中的私有成员
void visit1();
void visit2();
private:
Father *father;
};
class Father{
// 告诉编译器,Son类中的visit1成员函数是Father的友元,可以访问私有成员
friend void Son::visit1();
public:
Father();
public:
string m_bike;
private:
string m_car;
};
Father::Father() {
this->m_bike="自行车";
this->m_car="小汽车";
}
Son::Son() {
father=new Father;
}
//可以访问公有和私有成员
void Son::visit1() {
cout<<"可以访问"<<father->m_bike<<endl;
cout<<"可以访问"<<father->m_car<<endl;
}
//只可以访问公有成员
void Son::visit2() {
cout<<"可以访问"<<father->m_bike<<endl;
}
2.类做友元
class Father;
class Son{
public:
Son();
void visit();
private:
Father *father;
};
class Father{
// 告诉编译器,Son类是Father类的友元,可以访问其中的私有成员
friend class Son;
public:
Father();
public:
string m_bike;
private:
string m_car;
};
Father::Father() {
this->m_bike="自行车";
this->m_car="小汽车";
}
Son::Son() {
father=new Father;
}
//可以访问公有和私有成员
void Son::visit() {
cout<<"可以访问"<<father->m_bike<<endl;
cout<<"可以访问"<<father->m_car<<endl;
}
3.全局函数做友元
class Father{
// 告诉编译器,全局函数visit是Father类的友元,可以访问其中的私有成员
friend void visit(Father *father);
public:
Father(){
this->m_bike="自行车";
this->m_car="小汽车";
}
public:
string m_bike;
private:
string m_car;
};
void visit(Father *father){
cout<<"可以访问"<<father->m_bike<<endl;
cout<<"可以访问"<<father->m_car<<endl;
}