生活中你的家有客厅(Public),有你的卧室(Private)
客厅所有来的客人都可以进去,但是你的卧室是私有的,也就是说只有你能进去
但是呢,你也可以允许你的好闺蜜好基友进去。
在程序里,有些私有属性 也想让类外特殊的一些函数或者类进行访问,就需要用到友元的技术
友元的目的就是让一个函数或者类 访问另一个类中私有成员
友元的关键字为 friend
友元的三种实现
- 全局函数做友元
- 类做友元
- 成员函数做友元
全局函数做友元
// #include "onboard/qprod/utils/qjson.h"
#include "gtest/gtest.h"
class MyFriend{
friend void displayValues(MyFriend& fri);
// 私有values
public:
int age;
std::string name;
public:
MyFriend(int a, std::string n): age(a), name(n){}
};
void displayValues(MyFriend& fri){
std::cout << "Name: " << fri.name << std::endl;
std::cout << "Age: " << fri.age << std::endl;
}
TEST(MyFriend, displayValues){
MyFriend fri(12, "Damonxu");
displayValues(fri);
EXPECT_EQ(fri.age, 12);
}
int main(int argc, char** argv){
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
return 0;
}
成员函数做友元
class MyFriend{
public:
void printValues();
int age;
char gender;
YourFriend *friendPtr; // 指向你的朋友
};
class YourFriend{
friend void MyFriend::printValues();
public:
YourFriend(int age, std::string name){
this->age = age;
this->name = name;
}
int age;
std::string name;
};
void MyFriend::printValues(){
std::cout << "Age: " << age << std::endl;
std::cout << "Name: " << friendPtr->name << std::endl; // 访问你的朋友的名字
}
int main(){
MyFriend myFriend;
YourFriend yourFriend(12, "testing");
myFriend.printValues();
}
类做友元
class FristClass{
public:
FristClass();
void vistSecClassMem();
private:
SecondClass* sec;
};
class SecondClass{
friend class FristClass; //友元类
public:
SecondClass();
private:
int age;
std::string name;
char gender;
};
SecondClass::SecondClass(){
this->age = 10;
this->name = "zhangsan";
this->gender = 'M';
}
FristClass::FristClass(){
sec = new SecondClass;
}
void FristClass::vistSecClassMem(){
std::cout << "age:" << sec->age << std::endl;
std::cout << "name:" << sec->name << std::endl;
std::cout << "gender:" << sec->gender << std::endl;
}
void test_friend_class(){
FristClass* fc = new FristClass();
fc->vistSecClassMem();
}
int main(){
test_friend_class();
return 0;
}