全局函数做友元
//************ 友元 关键字为friend
@[全局函数做友元]
class Building
{
//goodGay全局函数是Building的好朋友,可以访问Building里面的私有成员
friend void goodGay(Building& building);
public:
Building()
{
m_sitting = "客厅";
m_bedroom = "卧室";
}
string m_sitting;
private:
string m_bedroom;
};
//全局函数
void goodGay(Building&building)
{
cout << "好基友的全局函数 正在访问: " << building.m_sitting << endl;
//私有属性在类外是无法访问的
cout << "好基友的全局函数 正在访问: " << building.m_bedroom << endl;
}
void test()
{
Building building;
goodGay(building);
}
int main()
{
test();
return 0;
}
类做有元
//*********类做有元
class Building; //这里只是告诉编译器,这个类我后面会写,先别报错
class GoodGay
{
public:
GoodGay(); //初始化函数,如果想在类外面进行初始化,仍然需要在类里面占一个位置
void visit(); //访问Building里面的属性
Building* building; //创建了一个指针
};
class Building
{
//GoodGay是本类的好朋友,可以访问本类的私有属性
friend class GoodGay;
public:
Building();
string m_sitting;
private:
string m_bedroom;
};
//类外写成员函数
Building::Building()
{
m_sitting = "客厅";
m_bedroom = "卧室";
}
GoodGay::GoodGay()
{
//创建建造物的对象
building = new Building; //new 后面加什么数据类型,就返回什么样的指针
}
void GoodGay::visit()
{
cout << "GoodGay 正在访问:" << building->m_sitting << endl;
}
void test()
{
GoodGay gg; //GoodGay::GoodGay() ---> Building::Building() --> void GoodGay::visit()
gg.visit();
}
int main()
{
test();
return 0;
}
成员函数做有元
//*********成员函数做有元
class Building;
class GoodGay
{
public:
GoodGay();
void visit(); //让这个函数可以building中的私有成员
void visit2();
Building* building;
};
class Building
{
//告诉编译器,GoodGay下的visit是本类的有元,可以访问本类的私有属性
friend void GoodGay::visit();
public:
Building();
string m_setting;
private:
string m_bedroom;
};
//类外实现成员函数
Building::Building()
{
m_setting = "客厅";
m_bedroom = "卧室";
}
GoodGay::GoodGay()
{
building = new Building; //创建一个类,就会自动调用初始化函数进行初始化 Building::Building()
}
void GoodGay::visit()
{
cout << "visit 在访问:" << building->m_setting <<endl;
cout << "visit 在访问:" << building->m_bedroom << endl;
}
void GoodGay::visit2()
{
cout << "visit2 在访问:" << building->m_setting << endl;
//cout << "visit2 在访问:" << building->m_bedroom << endl;
}
void test()
{
GoodGay gg;
gg.visit();
gg.visit2();
}
int main()
{
test();
return 0;
}