12.4 友元函数
类中的私有成员和保护成员是只能类内访问,但在某些特殊情况,我们希望类外也能访问,这就要用到友元技术。
在类中声明该函数并在前面加上friend关键字,这样函数就可以畅通无阻地访问私有和保护成员了。
12.4.1 全局函数做友元
#include<iostream>
#include<string>
using namespace std;
class building
{
friend void test1();
public:
building()
{
m_Sittingroom = "客厅";
m_Bedroom = "卧室";
m_Showerroom = "浴室";
}
public:
string m_Sittingroom;
private:
string m_Showerroom;
protected:
string m_Bedroom;
};
void test1()
{
building b;
cout << b.m_Sittingroom;
cout << b.m_Bedroom;
cout << b.m_Showerroom;
}
int main()
{
test1();
system("pause");
return 0;
}
正常情况下,test1()这个函数是不能访问私有和保护成员地,但在类中我们声明test1()是友元函数,这样就可以访问了。程序没有任何报错:
12.4.2 类做友元
#include<iostream>
#include<string>
using namespace std;
class building
{
friend class lover;
public:
building()
{
m_Sittingroom = "客厅";
m_Bedroom = "卧室";
m_Showerroom = "浴室";
}
public:
string m_Sittingroom;
private:
string m_Showerroom;
protected:
string m_Bedroom;
};
class lover
{
public:
building build;
void func()
{
cout << build.m_Bedroom << endl;
cout << build.m_Sittingroom << endl;
cout << build.m_Showerroom << endl;
}
};
int main()
{
lover love;
love.func();
system("pause");
return 0;
}
这里我们声明另外一个lover类做友元,那么lover类中地所有成员函数都能访问building里地所有成员了。程序没有任何报错:
12.4.3 成员函数做友元
可以只声明另一个类中地某个函数做友元。
这是需要在building类中的友元声明前先声明func函数,不然还是不能访问。所以这里我把lover类定义在了building类前面,并且是先声明了func()函数,之后再进行定义。
#include<iostream>
#include<string>
using namespace std;
class lover
{
public:
void func1();
};
class building
{
friend void lover::func1();
public:
building()
{
m_Sittingroom = "客厅";
m_Bedroom = "卧室";
m_Showerroom = "浴室";
}
public:
string m_Sittingroom;
private:
string m_Showerroom;
protected:
string m_Bedroom;
};
void lover::func1()
{
building build;
cout << build.m_Bedroom << endl;
cout << build.m_Sittingroom << endl;
cout << build.m_Showerroom << endl;
}
int main()
{
lover love;
love.func1();
system("pause");
return 0;
}
程序没有报错: