··················本来要学习的吃瓜吃了一下午
目录
3.1 全局函数做友元
3.2 友元类
3.3 成员函数做友元
三,友元
3.1 全局函数做友元
#include<iostream>
using namespace std;
class Building
{
friend void goodGay(Building* building);
//好朋友,可以访问buiding的全部成员
public:
Building()
{
m_SittingRoom = "客厅";
m_BedRoom = "卧室";
}
string m_SittingRoom;
private:
string m_BedRoom;
};
void goodGay(Building *building)
{
cout << "好基友的全局函数 正在访问:" << building->m_SittingRoom << endl;
cout << "好基友的全局函数 正在访问:" << building->m_BedRoom << endl;
}
void test01()
{
Building bding;
goodGay(&bding);
}
int main()
{
test01();
system("pause");
return 0;
}
3.2 友元类
#include<iostream>
#include<string>
using namespace std;
class Building;
class Goodgay
{
public:
Goodgay();
void visit();//参观函数,访问BUIDING中的属性
Building * building;
};
class Building
{
friend Goodgay;//GoodGAY类是BUILDING类的好朋友,可以访问BUILDING的私有成员
public:
Building();
string m_SittingRoom;
private:
string m_BedRoom;
};
Building::Building()//类外写成员函数
{
m_SittingRoom = "客厅";
m_BedRoom = "卧室";
}
Goodgay::Goodgay()
{
//创建一个建筑物的对象
building = new Building;//堆区创建一个BUILDING的对象
//构造函数解决初始化问题,所以?这是初始化?*building指向这个堆区对象
}
void Goodgay::visit()
{
cout << "好基友类正在访问:" << building->m_SittingRoom << endl;
cout << "好基友类正在访问:" << building->m_BedRoom << endl;
}
void test01()
{
Goodgay gg;
gg.visit();
}
int main()
{
test01();
system("pause");
return 0;
}
3.3 成员函数做友元
#include<iostream>
#include<string>
using namespace std;
class Building;
class Goodgay
{
public:
Goodgay();
void visit();//可以访问Buiding私有
void visit01();//不可以访问Buiding私有
Building * building;
};
class Building
{
//friend void visit();这种写法会将VISIT识别为一个全局函数,而不是Goodgay中的成员函数
friend void Goodgay::visit();
public:
Building();
string m_SittingRoom;
private:
string m_BedRoom;
};
Building::Building()//类外写成员函数
{
m_SittingRoom = "客厅";
m_BedRoom = "卧室";
}
Goodgay::Goodgay()
{
//创建一个建筑物的对象
building = new Building;//堆区创建一个BUILDING的对象,返回指针
//构造函数解决初始化问题,所以?这是初始化?building指向这个堆区对象
}
void Goodgay::visit()
{
cout << "好基友类visit 正在访问:" << building->m_SittingRoom << endl;
cout << "好基友类visit 正在访问:" << building->m_BedRoom << endl;
}
void Goodgay::visit01()
{
cout << "好基友类visit01 正在访问:" << building->m_SittingRoom << endl;
//cout << "好基友类visit01 正在访问:" << building->m_BedRoom << endl;
}
void test01()
{
Goodgay gg;
gg.visit();
gg.visit01();
}
int main()
{
test01();
system("pause");
return 0;
}
想让谁访问,就让谁FRIEND