友元
友元函数定义在外部,但有权访问类的所有私有成员和保护成员。
关键字: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();
}