当我们在类中定义完私有成员后,不能直接在类外调用。如果想在类外调用私有成员可使用友元。友元的使用可以分为下列三种情况:
1.全局函数做友元
代码示例
#include"iostream"
#include"string"
using namespace std;
//建筑物类
class Building
{
friend void goodgay(Building*building);//goodgay是building类的好朋友,可以访问building类中的私有成员
public:
Building()
{
m_sittingroom = "客厅";
m_bedroom = "卧室";
}
public:
string m_sittingroom;
private:
string m_bedroom;
};
void goodgay(Building*building)//全局函数做友元
{
cout << "好基友全局函数 正在访问:" << building->m_sittingroom << endl;
cout << "好基友全局函数 正在访问:" << building->m_bedroom << endl;
}
void test()
{
Building building;
goodgay(&building);
}
int main()
{
test();
system("pause");
return 0;
}
注:直接将全局函数复制到类内,并在函数语句前加关键字friend,后加分号。这样全局函数就可以调用类内的私有成员。
2.类做友元
代码示例:
#include"iostream"
#include"string"
using namespace std;
class Building
{
friend class goodgay;//goodgay类是本类的好朋友,可以访问本类中的私有成员
public:
Building()
{
m_sittingroom = "客厅";
m_bedroom = "卧室";
}
public:
string m_sittingroom;
private:
string m_bedroom;
};
class goodgay
{
public:
goodgay()
{
building = new Building;
}
public:
void visit()
{
cout << "好基友类正在访问:" << building->m_sittingroom << endl;
cout << "好基友类正在访问:" << building->m_bedroom << endl;//访问私有属性
}
Building *building;
};
void test01()
{
goodgay gg;
gg.visit();
}
int main()
{
test01();
system("pause");
return 0;
}
注:在本例中我们定义了两个类:Building类和goodgay类,在Building类中m_bedroom为私有成员,goodgay类中visit函数想要访问Building类中的私有成员就必须用到友元,在Building类中加入语句 friend class goodgay();表示类goodgay是类Building的好朋友,可以访问其私有成员。
3.成员函数做友元
代码示例:
#include"iostream"
using namespace std;
#include"string"
class Building;
class goodgay
{
public:
goodgay();
void visit1();
Building *building;
};
class Building
{
friend void goodgay::visit1();//告诉编译器goodgay类下的visit1函数作为本类的好朋友,可以访问私有成员
public:
Building()
{
m_sittingroom = "客厅";
m_bedroom = "卧室";
}
public:
string m_sittingroom;
private:
string m_bedroom;
};
goodgay::goodgay()
{
building = new Building;
}
void goodgay::visit1()//让visit1函数可以访问Building中私有成员
{
cout << "visit1函数正在访问:" << building->m_sittingroom << endl;
cout << "visit1函数正在访问:" << building->m_bedroom << endl;
}
void test01()
{
goodgay gg;
gg.visit1();
}
int main()
{
test01();
system("pause");
return 0;
}