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;

}

相关推荐
Dxxyyyy34 分钟前
零基础学JAVA--Day34(Map接口+HashTable+HashMap+TreeSet+TreeMap+开发中如何选择集合实现类?(重要))
java·开发语言
rainFFrain1 小时前
qt显示类控件---QProgressBar
开发语言·qt
鑫—萍1 小时前
C/C++精品算法——双指针(1)
c语言·c++·算法
rainFFrain1 小时前
qt输入类控件---QComboBox/QSpinBox
开发语言·qt
2501_941111891 小时前
低延迟系统C++优化
开发语言·c++·算法
未来之窗软件服务1 小时前
自建开发工具IDE(二)文件托拽读取——东方仙盟炼气期
开发语言·前端·javascript·仙盟创梦ide·东方仙盟
Hello_WOAIAI2 小时前
4.2 python多线程编程:threading 模块深度解析
开发语言·python
2501_941111992 小时前
C++中的装饰器模式变体
开发语言·c++·算法
树下水月2 小时前
python 连接hive2 数据库
开发语言·数据库·python
Tom4i2 小时前
Kotlin 中的 inline 和 reified 关键字
android·开发语言·kotlin