c++--友元

2021/8/4 22:09:52

本文主要是介绍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();
}


这篇关于c++--友元的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程