在程序中,有些私有属性想让类外特殊的一些函数或者类进行访问,就需要用到友元的技术。
友元的目的就是让一个函数或者类访问另一个类中私有成员。
友元的关键字为friend
全局函数做友元
#include<iostream>
using namespace std;
class Building
{
public:
//goodfriend全局函数是Building的好朋友,可以访问Building中的私有成员
friend void goodfriend(Building* building);
Building()
{
m_SittingRoom = "客厅";
m_BedRoom = "卧室";
}
string m_SittingRoom;
private:
string m_BedRoom;
};
void goodfriend(Building* building)
{
cout << "好朋友全局函数正在访问:" << building->m_SittingRoom << endl;
cout << "好朋友全局函数正在访问:" << building->m_BedRoom << endl;//访问私有成员
}
void test()
{
Building building;
goodfriend(&building);
}
int main()
{
test();
system("pause");
return 0;
}
类做友元
#include<iostream>
using namespace std;
class Building;//声明
class goodfriend
{
public:
goodfriend();
void visit();//参观函数,访问Building中的属性
private:
Building* building;
};
class Building
{
//告诉编译器goodfriend类是Building类的好朋友,可以访问Building类中私有内容
friend class goodfriend;
public:
Building();
public:
string m_SittingRoom;//客厅
private:
string m_BedRoom;//卧室
};
//类外写成员函数
Building::Building()
{
this->m_SittingRoom = "客厅";
this->m_BedRoom = "卧室";
}
goodfriend::goodfriend()
{
//创建建筑物对象
building = new Building;
}
void goodfriend::visit()
{
cout << "好朋友正在访问" << building->m_SittingRoom << endl;
cout << "好朋友正在访问" << building->m_BedRoom << endl;//访问Building类中私有内容
}
void test()
{
goodfriend gg;
gg.visit();
}
int main()
{
test();
system("pause");
return 0;
}
成员函数做友元
#include<iostream>
using namespace std;
class Building;//声明
class goodfriend
{
public:
goodfriend();
void visit1();//让visit1函数可以访问Building中私有成员
void visit2();//让visit2函数不可以访问Building中私有成员
Building* building;
};
class Building
{
//告诉编译器goodfriend类中的visit1成员函数是Building类的好朋友,可以访问Building类中私有内容
friend void goodfriend::visit1();
public:
Building();
public:
string m_SittingRoom;//客厅
private:
string m_BedRoom;//卧室
};
//类外写成员函数
Building::Building()
{
m_SittingRoom = "客厅";
m_BedRoom = "卧室";
}
goodfriend::goodfriend()
{
//创建建筑物对象
building = new Building;
}
void goodfriend::visit1()
{
cout << "visit1正在访问" << building->m_SittingRoom << endl;
cout << "visit1正在访问" << building->m_BedRoom << endl;//访问Building类中私有内容
}
void goodfriend::visit2()
{
cout << "visit2正在访问" << building->m_SittingRoom << endl;
//cout << "visit2正在访问" << building->m_BedRoom << endl;//无法访问Building类中私有内容
}
void test()
{
goodfriend gg;
gg.visit1();
gg.visit2();
}
int main()
{
test();
system("pause");
return 0;
}