C++ 面向对象编程:友元、
友元:让一个类或函数,能够访问另一个类的私有成员。友元关键字为friend。
友元有三种:第一种是全局函数作为友元,第二种是类作为友元,第三种是成员函数作为友元
第一种是全局函数作为友元,见以下代码:
#include<iostream>
#include<string>
using namespace std;
class People {
friend void getfriendmsg(People* p);
public:
People() {
msg1 = "aa";
msg2 = "bb";
}
public:
string msg2;
private:
string msg1;
};
void getfriendmsg(People *p) {
cout << p->msg2 << endl;
cout << p->msg1 << endl;
}
int main() {
People p;
return 0;
}
第二种是类作为友元,让另一个类去访问类的私有变量,可见以下代码:
#include<iostream>
#include<string>
using namespace std;
class People;
class People1 {
public:
People1() {
}
void getmsg(People* p);
};
class People {
friend class People1;
public:
People() {
msg1 = "aa";
msg2 = "bb";
}
public:
string msg2;
private:
string msg1;
};
void People1::getmsg(People* p) {
cout << p->msg2 << endl;
cout << p->msg1 << endl;
}
int main() {
People p;
People1 p1;
p1.getmsg(&p);
return 0;
}
第三种是成员函数作为友元
#include<iostream>
#include<string>
using namespace std;
class People;
class People1 {
public:
People1() {
}
void getmsg2(People* p);
void getmsg12(People* p);
};
class People {
friend void People1::getmsg12(People* p);
public:
People() {
msg1 = "aa";
msg2 = "bb";
}
public:
string msg2;
private:
string msg1;
};
void People1::getmsg12(People* p) {
cout << p->msg2 << endl;
cout << p->msg1 << endl;
}
void People1::getmsg2(People* p) {
cout << p->msg2 << endl;
}
int main() {
People p;
People1 p1;
p1.getmsg2(&p);
p1.getmsg12(&p);
return 0;
}