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;

}

相关推荐
今儿敲了吗21 小时前
46| FBI树
数据结构·c++·笔记·学习·算法
oem11021 小时前
C++中的访问者模式变体
开发语言·c++·算法
SuperEugene1 天前
JS/TS 编码规范实战:Vue 场景变量 / 函数 / 类型标注避坑|编码语法规范篇
开发语言·javascript·vue.js
暮冬-  Gentle°1 天前
C++中的工厂方法模式
开发语言·c++·算法
乱世军军1 天前
把 Python 3.13 降级到 3.11
开发语言·python
本喵是FW1 天前
C语言手记2
c语言·开发语言
fy121631 天前
GO 快速升级Go版本
开发语言·redis·golang
共享家95271 天前
Java入门(String类)
java·开发语言
0xDevNull1 天前
Spring Boot 循环依赖解决方案完全指南
java·开发语言·spring
bbq粉刷匠1 天前
Java--多线程--单例模式
java·开发语言·单例模式