友元
友元分为:友元函数和友元类
友元提供了一种突破封装的方式,有时提供了便利。但是友元会增加耦合度,破坏了封装,所以友元不宜多 用。
全局函数做友元函数
-
全局函数写到类中做声明 并且最前面写关键字 friend
-
友元函数可访问类的私有成员,但不是类的成员函数
-
友元函数不能用const修饰 友元函数可以在类定义的任何地方声明,不受类访问限定符限制
-
一个函数可以是多个类的友元函数
-
友元函数的调用与普通函数的调用和原理相同
#include<iostream> #include<string> using namespace std; class Building { //让全局好基友函数变为我的好朋友 友元函数 friend void goodGay(Building *building); public: Building() { this->m_SittingRoom = "客厅"; this->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 test01() { Building *building=new Building; goodGay(building); } int main() { test01(); system("pause"); return 0; }
类作为友元类
- 友元关系不能被继承
- 友元关系是单向的,类A是类B的朋友,但类B不一定是类A的朋友。
- 友元关系不具有传递性,类B是类A的朋友,类C是类B的朋友,但类C不一定是类A的朋友
#include
#include
using namespace std;
class Building;
class goodGay
{
public:
goodGay();
void visit();
private:
Building * building;
};
class Building
{
//让好基友类 作为Building的好朋友
friend class goodGay;
public:
Building();
public:
string m_SiteingRoom;//客厅
private:
string m_BedRoom;//卧室
};
goodGay::goodGay()
{
building = new Building;
}
void goodGay::visit()
{
cout << "好基友正在访问:" << this->building->m_SiteingRoom << endl;
cout << "好基友正在访问:" << this->building->m_BedRoom<< endl;
}
Building::Building()
{
this->m_SiteingRoom = "客厅";
this->m_BedRoom = "卧室";
}
void test01()
{
goodGay gg;
gg.visit();
}
int main()
{
test01();
system("pause");
return 0;
}
成员函数作为友元函数
#include<iostream>
#include<string>
using namespace std;
//只让visit可以作为Buildingde的好朋友,visit2不可以访问私有属性
class Building;
class goodGay
{
public:
goodGay();
void visit();
void visit2();
private:
Building * building;
};
class Building
{
//让成员函数visit作为友元函数
friend void goodGay:: visit();
public:
Building();
public:
string m_SiteingRoom;//客厅
private:
string m_BedRoom;//卧室
};
goodGay::goodGay()
{
building = new Building;
}
void goodGay::visit()
{
cout << "好基友正在访问:" << this->building->m_SiteingRoom << endl;
cout << "好基友正在访问:" << this->building->m_BedRoom<< endl;
}
void goodGay::visit2()
{
cout << "好基友正在访问:" << this->building->m_SiteingRoom << endl;
//cout << "好基友正在访问:" << this->building->m_BedRoom << endl;
}
Building::Building()
{
this->m_SiteingRoom = "客厅";
this->m_BedRoom = "卧室";
}
void test01()
{
goodGay gg;
gg.visit();
gg.visit2();
}
int main()
{
test01();
system("pause");
return 0;
}