在程序中 有些私人属性也想让类外特殊的一些函数或者类进行访问,就是要用到友元的技术
友元的目的是让一个函数或者类 访问 另一个私有成员
友元的关键字 :friend
友元的三种实现:
1.全局函数做友元
2.类做友元
3.成员函数做友元
1.全局函数做友元
#include<iostream>
#include<string>
using namespace std;
class Building
{
//告诉编译器全局函数GoodGay是building 的好朋友可以访问私有属性
friend void GoodGay( Building* building);
public:
Building()
{
this->m_Sitingroom = "客厅";
this->m_Bedroom = "卧室";
}
public:
string m_Sitingroom;
private:
string m_Bedroom;
};
void GoodGay(Building* building)
{
cout << "访问:" << building->m_Sitingroom << endl;
cout << "访问:" << building->m_Bedroom << endl;
}
void test01()
{
Building b;
GoodGay(&b);
}
int main()
{
test01();
system("pause");
return 0;
}
2.类做有元函数
#include<iostream>
#include<string>
using namespace std;
class Building;
class GoodGay
{
public:
GoodGay();
void visit();
private:
Building* b; //Buding 类型的指针
};
class Building
{ //告诉编译器Gooday是building的好朋友 可以访问building的私有属性
friend class GoodGay;
public:
Building();
string SittingRoom;
private:
string BedRoom;
};
GoodGay::GoodGay()//GoodGay作用域下的构建函数GoodGay
{
b = new Building; //堆区新开辟一个区域
}
Building::Building()
{
SittingRoom = "客厅";
BedRoom = "卧室";
}
void GoodGay::visit()
{
cout << "参观:" << b->SittingRoom << endl;
cout << "参观:" << b->BedRoom << endl;
}
void test()
{
GoodGay gooday;
//访问goodday中visit函数即可
gooday.visit();
}
int main()
{
test();
system("pause");
return 0;
}
#include<iostream>
#include<string>
using namespace std;
class Building;
class GoodGay
{
public:
GoodGay();
void visit01();//让visit01 可以访问Building中是私有属性
void visit02();//让visit02 不 可以访问Building中是私有属性
Building * building;
};
class Building
{ //告诉编译器 GoodGay作用域下的visit01是Building 的好朋友
friend void GoodGay::visit01();//让visit01可以访问Building下的私有属性
public:
Building()
{
Sittingroom = "客厅";
Bedroom = "卧室";
}
public:
string Sittingroom;
private:
string Bedroom;
};
GoodGay::GoodGay()
{
building = new Building;//创建一个新的对象Building在堆区,并且指针p管理该区域
}
void GoodGay::visit01()
{
cout << "visit01访问的是:" << building->Sittingroom << endl;
cout << "visit01访问的是:" << building->Bedroom << endl;
}
void GoodGay::visit02()
{
cout << "visit01访问的是:" << building->Sittingroom << endl;
//cout << "visit01访问的是:" << building->Bedroom << endl;
}
void test01()
{
GoodGay gg;
gg.visit01();
gg.visit02();
}
int main()
{
test01();
system("pause");
return 0;
}