1. 程式人生 > 其它 >c++--友元

c++--友元

友元

友元函式定義在外部,但有權訪問類的所有私有成員和保護成員。

關鍵字:friend

1.全域性函式做友元

class building {
public:
	//初始化
	building(string a,string b):m_sittingroom(a),m_bedroom(b){}
	string m_sittingroom;
	friend void fun();//友元
private:
	string m_bedroom;
};
void fun(){
	building p("客廳", "臥室");
	cout << p.m_sittingroom << endl;
	cout << p.m_bedroom << endl;//私有屬性
}

2.類做友元

class student;
class grade {
public:
	grade();//建構函式類外定義
	void test();
private:
	student *p;
};
class student {
	friend class grade;
public:
	student();
	string m_name;
private:
	int m_age;
};
grade::grade(){
	p = new student;
	
}
student::student() {
	m_name = "劉翔";
	m_age = 30;
}
void grade::test() {

	cout <<p->m_name << endl;
	cout << p->m_age << endl;
}
void fun() {
	grade p;
	p.test();
}

3.成員函式做友元

friend 型別(void,int) 類名:: 函式名

class student;
class grade {

public:
	grade();
	int m_num;
	student* p;
	void fun1();

};
class student {
	
public:
	student();
	int name;
private:
	//friend class grade;
	friend void grade::fun1();
	int age;
};
grade::grade() {
	p = new student;
}
student::student() {
	this->age = 12;
	this->name = 10;
}
void grade::fun1() {
	cout << p->name << endl;
	cout << p->age << endl;
}
void test() {
	grade p;
	p.fun1();
}