1.1 友元概述
- 在程序里,有些私有属性 也想让类外特殊的一些函数或者类进行访问,就需 要用到友元的技术。
- 友元的目的就是让一个函数或者类 访问另一个类中私有成员。
- 相当于你的有些事情所有人都可以知道,但有些事情只能和你的朋友讨论。
友元的关键字为friend
友元的三种实现: - 全局函数做友元
- 类做友元
- 成员函数做友元
1.2 全局函数做友元
#include<iostream>
#include<string>
using namespace std;
#include<string>
class h{
friend void Mona(h* a);
public:
string best_book = "薄荷双生" ;
private:
string best_idol = "道枝骏佑" ;
};
void Mona(h *a){
cout << "我最喜欢的idol是:" << a->best_idol << endl;
cout << "我最喜欢的书是:" << a->best_book << endl;
}
int main() {
h H;
Mona(&H);
system("pause");
return 0;
}
- 告诉编译器 Mona全局函数 是 h类的好朋友,可以访问类中的私有内容
输出:
我最喜欢的idol是:道枝骏佑
我最喜欢的书是:薄荷双生
请按任意键继续. . .
1.3 类做友元
//可以进行先声明类,再定义
class h00;
class h01{
public:
h01();
void visit_h00();
private:
h00 *h;
};
class h00{
friend class h01;
public:
h00();
string best_book;
private:
string best_idol;
};
//类外定义构造函数
h01::h01(){
h = new h00;
}
//类外定义成员函数
void h01::visit_h00(){
cout << "我最喜欢的idol是:" << h->best_idol << endl;
cout << "我最喜欢的书是:" << h->best_book << endl;
}
h00::h00()
{
best_book = "薄荷双生" ;
best_idol = "道枝骏佑" ;
}
//void Mona(h *a){
// cout << "我最喜欢的idol是:" << a->best_idol << endl;
// cout << "我最喜欢的书是:" << a->best_book << endl;
//}
int main() {
h01 H;
H.visit_h00();
system("pause");
return 0;
}
输出:
我最喜欢的idol是:道枝骏佑
我最喜欢的书是:薄荷双生
请按任意键继续. . .
1.4 成员函数做友元
class h00{
friend void h01::visit_h00_0();
public:
h00();
string best_book;
private:
string best_idol;
};
void h01::visit_h00_0(){
cout << "我最喜欢的idol是:" << h->best_idol << endl;
cout << "我最喜欢的书是:" << h->best_book << endl;
}
//没有再类内声明其为友元函数,故不可以访问私有成员
void h01::visit_h00_1(){
// cout << "我最喜欢的idol是:" << h->best_idol << endl;
cout << "我最喜欢的书是:" << h->best_book << endl;
}
输出:
我最喜欢的idol是:道枝骏佑
我最喜欢的书是:薄荷双生
我最喜欢的书是:薄荷双生
请按任意键继续. . .