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;

}

相关推荐
言乐64 小时前
Python根据关联词搜索模型
开发语言·人工智能·python·机器学习·django
纪念 2294 小时前
C++ string(一)
android·开发语言·c++
一木 之林4 小时前
阿里云百炼与通义千问接入
开发语言·php
纪念 2294 小时前
C++算法(二)
开发语言·c++·算法
Wang's Blog4 小时前
Java 项目实战: 外卖平台优化-Nginx概述与源码编译安装
java·开发语言·nginx
笨笨饿6 小时前
#141_ Codex 本地 AI 代理工具链工作流重构:Headroom、Scrapling、Archify 统一接入
开发语言·人工智能·stm32·单片机·嵌入式硬件·ui·重构
承渊政道8 小时前
星空组网+Python实战:在另一台电脑上查看CSV报表
运维·开发语言·python·csv·星空组网
Liquad Li9 小时前
Salesforce 主流认证方式、流程、适用场景
开发语言·salesforce
LOVE️YOU12 小时前
Python 中 Tuple 为什么有时可 Hash,有时不可 Hash?
开发语言·python·哈希算法
李永奉13 小时前
C语言-指针函数与函数指针及回调函数的使用
c语言·开发语言