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;

}

相关推荐
Dear.爬虫几秒前
Golang中逃逸现象, 变量“何时栈?何时堆?”
开发语言·后端·golang
愚润求学18 分钟前
【贪心算法】day6
c++·算法·leetcode·贪心算法
沐怡旸37 分钟前
【底层机制】右值引用是什么?为什么要引入右值引用?
c++·面试
编码浪子40 分钟前
趣味学RUST基础篇(构建一个命令行程序2重构)
开发语言·重构·rust
echoarts1 小时前
MATLAB R2025a安装配置及使用教程(超详细保姆级教程)
开发语言·其他·matlab
scx201310041 小时前
P13929 [蓝桥杯 2022 省 Java B] 山 题解
c++·算法·蓝桥杯·洛谷
阿方.9181 小时前
《数据结构全解析:栈(数组实现)》
java·开发语言·数据结构
CYRUS_STUDIO2 小时前
LLVM 不止能编译!自定义 Pass + 定制 clang 实现函数名加密
c语言·c++·llvm
CYRUS_STUDIO2 小时前
OLLVM 移植 LLVM 18 实战,轻松实现 C&C++ 代码混淆
c语言·c++·llvm
落羽的落羽2 小时前
【C++】简单介绍lambda表达式
c++·学习