Contents
Some private members may need to be accessed by certain functions or classes outside the class. Friends are used for this purpose.
The keyword for friends is fiend
Friends can be implemented in three ways:
- A global function as a friend
- A class as a friend
- A member function as a friend
One: A Global Function as a Friend
Place the declaration of the global function inside the class definition and add the keyword friend before it.
Example: friend void func(Person *person);
class Person{
//goodFriend全局函数可以访问Person中的私有成员
friend void goodFriend(Person *person);
public:
Person(){
m_Name = "Huffie";
m_Money = 0;
}
public:
string m_Name;
private:
double m_Money;
};
void goodFriend(Person *person){
cout << "Friends is getting:" << person->m_Name << endl;
cout << "Friends is getting:" << person->m_Money << endl;
}
Two: A Class as a Friend
Syntax: friend class className;
#include<iostream>
#include<string>
using namespace std;
//Person类的定义
class Person{
friend class goodFriend;
public:
Person();
public:
string m_Name;
private:
double m_Money;
};
Person::Person(){
m_Name = "Huffie";
m_Money = 100;
}
//goodFriend类的定义
class goodFriend{
public:
goodFriend();
void get(); //获取函数,获取Person中的属性
Person * person;
};
goodFriend::goodFriend(){
person = new Person;
}
void goodFriend::get(){
cout << "goodFriend类正在访问:" << person->m_Name << endl;
cout << "goodFriend类正在访问:" << person->m_Money << endl;
}
//测试函数
void test01(){
goodFriend gf;
gf.get();
}
int main(){
test01();
system("pause");
return 0;
}
Three: A Member Function as a Friend
Example: friend void className::func();
#include<iostream>
#include<string>
using namespace std;
class Person;
class goodFriend{
public:
goodFriend();
void get1(); //让get函数可以访问Person中私有成员
void get2(); //让get函数不可以访问Person中私有成员
Person * person;
};
class Person{
friend void goodFriend::get1();
public:
Person();
string m_Name;
private:
double m_Money;
};
Person::Person(){
m_Name = "Huffie";
m_Money = 100;
}
goodFriend::goodFriend(){
person = new Person;
}
void goodFriend::get1(){
cout << "get函数正在访问:" << person->m_Name << endl;
cout << "get函数正在访问:" << person->m_Money << endl;
}
void goodFriend::get2(){
cout << "get函数正在访问:" << person->m_Name << endl;
//cout << "get函数正在访问:" << person->m_Money << endl;
}
void test(){
goodFriend gf;
gf.get1();
gf.get2();
}
int main(){
test();
system("pause");
return 0;
}
Reference: A Meticulously Crafted Course by Heima Programmer | C++ Tutorial from 0 up to 1: An Introduction to Programming, Making Programming Easier to Learn Link: https://www.bilibili.com/video/BV1et411b73Z

Comments