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;

}

相关推荐
Liekkas Kono10 分钟前
RapidOCR Python 贡献指南
开发语言·python·rapidocr
张张努力变强17 分钟前
C++ STL string 类:常用接口 + auto + 范围 for全攻略,字符串操作效率拉满
开发语言·数据结构·c++·算法·stl
xyq202419 分钟前
Matplotlib 绘图线
开发语言
小镇敲码人21 分钟前
探索CANN框架中TBE仓库:张量加速引擎的优化之道
c++·华为·acl·cann·ops-nn
m0_6948455723 分钟前
tinylisp 是什么?超轻量 Lisp 解释器编译与运行教程
服务器·开发语言·云计算·github·lisp
平安的平安25 分钟前
面向大模型算子开发的高效编程范式PyPTO深度解析
c++·mfc
June`26 分钟前
muduo项目排查错误+测试
linux·c++·github·muduo网络库
春日见28 分钟前
如何创建一个PR
运维·开发语言·windows·git·docker·容器
C++ 老炮儿的技术栈31 分钟前
VS2015 + Qt 实现图形化Hello World(详细步骤)
c语言·开发语言·c++·windows·qt
派葛穆38 分钟前
Python-批量安装依赖
开发语言·python