目录
在程序里,有些私有属性也想让某些特殊函数或类进行访问,就需要使用友元技术。因此,友元的目的就是让一个函数或类访问一个类中的私有成员。友元的关键字:friend
一、全局函数做友元
在类中对友元全局函数做如下声明:friend 返回值类型 友元全局函数名();
#include <iostream>
using namespace std;
class Student {
friend void fidAge(); //在类中声明全局函数的友元,使全局函数能够访问该类的私有成员变量
public:
Student() {
age = 18;
}
private:
int age; //定义一个私有成员变量
};
//定义一个全局函数访问类的私有成员变量
void fidAge() {
Student S1;
cout << "类私有成员变量age的值:" << S1.age << endl;
}
int main() {
fidAge();
system("pause");
return 0;
}
类私有成员变量age的值:18
请按任意键继续. . .
二、类做友元
在类中对友元类做如下声明:friend class 类名;
#include <iostream>
using namespace std;
#include<string>
class Phone {
friend class Student; //在类中声明另一个类的友元,使该类能够访问另一类的私有成员变量
public:
Phone() {
PName = "XiaoMi";
}
private:
string PName;
};
class Student {
public:
Student() {
age = 18;
//在该类中访问另一个类的私有成员变量
cout << "另一个类的私有成员变量PName的值:" << m_Phone.PName << endl;
}
Phone m_Phone;
private:
int age; //定义一个私有成员变量
};
//定义一个全局函数访问类的私有成员变量
void fidAge() {
Student S1;
}
int main() {
fidAge();
system("pause");
return 0;
}
另一个类的私有成员变量PName的值:XiaoMi
请按任意键继续. . .
三、成员函数做友元
在类中对另一个类的成员函数做友元声明:friend 返回值类型 另一类名::另一类的成员函数名();
#include <iostream>
using namespace std;
#include<string>
class Phone;
class Student {
public:
Student();
void reads();
private:
Phone *m_Phone;
int age; //定义一个私有成员变量
};
class Phone {
friend void Student::reads(); //在类中声明另一个类的成员函数做友元,使另一个类的该成员函数能够访问另一类的私有成员变量
public:
Phone() {
PName = "XiaoMi";
}
private:
string PName;
};
//类外定义类Student的构造函数
Student::Student() {
age = 18;
m_Phone = new Phone;
}
//类外定义类Student的成员函数
void Student::reads() {
//在该类的成员函数中访问另一个类的私有成员变量
cout << "另一个类的私有成员变量PName的值:" << m_Phone->PName << endl;
}
void fidAge() {
Student S1;
S1.reads();
}
int main() {
fidAge();
system("pause");
return 0;
}
另一个类的私有成员变量PName的值:XiaoMi
请按任意键继续. . .