C++中三種友元的示例

關於C++友元。
友元——可以訪問私有
1.全局函數做友元
2.類做友元
3.成員函數做友元

#include <iostream>
#include <string>
using namespace std;
//友元——可以訪問私有
//1.全局函數做友元
//2.類做友元
//3.成員函數做友元

class Building;
class Gay {
public:
	Gay();
	void friendvisit();	//可以訪問私有
	void normalvisit();	//不可以訪問私有
	Building* building;
};
class Building {
	friend void goodGay(Building& building);
	friend class GoodGay;
	friend void Gay::friendvisit();
public:
	Building() : m_Sittingroom("客廳"), m_Bedroom("臥室") {}
public:
	string m_Sittingroom;
private:
	string m_Bedroom;
};

class GoodGay {
public:
	GoodGay();
	Building* building;
	void visit();	//訪問公共和私有屬
};
GoodGay::GoodGay() {
	building = new Building;
}
void GoodGay::visit() {
	cout << "好基友類,正在訪問:" << building->m_Sittingroom << endl;
	cout << "好基友類,正在訪問:" << building->m_Bedroom << endl;
}

Gay::Gay() {
	building = new Building;
}
void Gay::friendvisit() {
	cout << "基友的成員函數,正在訪問:" << building->m_Sittingroom << endl;
	cout << "基友的成員函數,正在訪問:" << building->m_Bedroom << endl;
}
void Gay::normalvisit() {
	cout << "基友的成員函數,正在訪問:" << building->m_Sittingroom << endl;
	//cout << "基友的成員函數,正在訪問:" << building->m_Bedroom << endl;
}


//全局函數
void goodGay(Building &building) {
	cout << "好基友的全局函數,正在訪問:" << building.m_Sittingroom << endl;
	cout << "好基友的全局函數,正在訪問:" << building.m_Bedroom << endl;
}

int main() {
	Building b;
	goodGay(b);
	GoodGay g;
	g.visit();
	Gay gg;
	gg.friendvisit();
	gg.normalvisit();
	system("pause");
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章