C++友元函数
友元的三种实现
1.全局函数做友元
2.类做友元
3.成员函数做友元
1.全局函数做友元
#include<iostream>
#include<string>
using namespace std;
class Building
{
//goodgay全局函数是类Building的好朋友,可以访问类Building中私有成员
friend void 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 test1()
{
Building building;
goodgay(&building);
}
int main()
{
test1();
return 0;
}
2.类做友元
#include<iostream>
#include<string>
using namespace std;
class Building;
class goodgay
{
public:
goodgay();
void visit(); //参观函数访问Building中的属性
private:
Building *building;
};
class Building
{
//goodgay类是本类的好朋友,可以访问本类中私有成员
friend class goodgay;
public:
Building();
public:
string m_SittingRoom;
private:
string m_BedRoom;
};
//类外写成员函数
Building::Building()
{
m_SittingRoom="客厅";
m_BedRoom="卧室";
}
goodgay::goodgay()
{
//创建建筑物对象
building=new Building;
}
void goodgay::visit()
{
cout<<"好基友类正在访问:"<<building->m_SittingRoom<<endl;
cout<<"好基友类正在访问:"<<building->m_BedRoom<<endl;
}
void test1()
{
goodgay gg;
gg.visit();
}
int main()
{
test1();
return 0;
}
3.成员函数做友元
#include<iostream>
#include<string>
using namespace std;
class Building;
class goodgay
{
public:
goodgay();
void visit(); //visit函数可以访问Building中的私有成员
void visit2();//visit函数不可以访问Building中的私有成员
private:
Building *building;
};
class Building
{
//告诉编译器goodgay类下的visit成员函数作为本类的好朋友,可以访问私有成员
friend void goodgay::visit();
friend void goodgay::visit2();
public:
Building();
public:
string m_SittingRoom;
private:
string m_BedRoom;
};
//类外实现成员函数
Building::Building()
{
m_SittingRoom="客厅";
m_BedRoom="卧室";
}
goodgay::goodgay()
{
building=new Building;
}
void goodgay::visit()
{
cout<<"visit函数正在访问:"<<building->m_SittingRoom<<endl;
cout<<"visit函数正在访问:"<<building->m_BedRoom<<endl;
}
void goodgay::visit2()
{
cout<<"visit函数正在访问:"<<building->m_SittingRoom<<endl;
cout<<"visit函数正在访问:"<<building->m_BedRoom<<endl;
}
void test1()
{
goodgay gg;
gg.visit();
gg.visit2();
}
int main()
{
test1();
return 0;
}