C++ 友元

朋友可访问自己的东西,大概就这么个意思。即某类的友元类可访问该类的所有变量以及函数,或友元函数可以访问该类的变量以及函数,在朋友眼中没有任何隐藏,可谓时赤裸相对,肝胆相照,生生挚友。

注意:记得前置声明,不然很容易报错说没有定义声明;

友元函数:

cpp 复制代码
// 【3】编写一个程序包含两个类,一个为Remotera类用来表示(万能)遥控器,一个为TV类用来表示电视机,要求遥控器能控制电视机,提供如下功能:
// ·电视机本身提供诸如setChannel(0、setVolume0等接口来修改频道和音量
// ·遥控器(万能)可控制电视机,但诸如开灯、降低空调温度等操作对电视机无效
#include <iostream>
#include <string.h>
using namespace std;

class TV;
class RemoteControl;

class RemoteControl
{
public:
    void setVolume(TV &tv, int volume); 
    void setChannel(TV &tv, int channel);
};

class TV
{
public:
    TV() {}
    void show()
    {
        cout << "TV volume=" << volume << endl;
        cout << "TV channel=" << channel << endl;
    }

private:
    friend void RemoteControl::setChannel(TV &tv, int channel); //友元函数
    friend void RemoteControl::setVolume(TV &tv, int volume);
    int volume;
    int channel;
};

void RemoteControl::setVolume(TV &tv, int volume)
{
    tv.volume = volume;
}

void RemoteControl::setChannel(TV &tv, int channel)
{
    tv.channel = channel;
    cout << "友元函数调用: "<< endl;
    tv.show();
}


int main(int argc, char const *argv[])
{
    TV tv;
    RemoteControl rc;
    rc.setVolume(tv, 10);
    rc.setChannel(tv, 10);
    tv.show();
    return 0;
}

友元类:

cpp 复制代码
// 练习:利用友元类的技术点,让两个类,互为友元,并访问对方的私有成员。遇到语法错误,思考如何解决?
#include <iostream>
#include <string.h>
using namespace std;

class A;
class B;

class A
{
public:
    A(int a)
    {
        this->a = a;
    }
    void show_a(B &b);
private:
    int a;
    friend class B;
};
class B
{
public:
    B(int b)
    {
        this->b = b;
    }
    void show_b(A &a);


private:
    int b;
    friend class A;
};

void B::show_b(A &a)
{
    a = 10;
    cout << "a=" << a.a << endl;
    cout << "b=" << b << endl;
}

void A::show_a(B &b)
{
    b = 20;
    cout << "a=" << a << endl;
    cout << "b=" << b.b << endl;
}

int main(int argc, char const *argv[])
{
    A a(10);
    B b(20);
    a.show_a(b);
    b.show_b(a);
    return 0;
}
相关推荐
-To be number.wan20 小时前
C++ 赋值运算符重载:深拷贝 vs 浅拷贝的生死线!
前端·c++
疯狂的挖掘机20 小时前
记一次基于QT的图片操作处理优化思路(包括在图上放大缩小,截图,画线,取值等)
开发语言·数据库·qt
cnxy18820 小时前
围棋对弈Python程序开发完整指南:步骤4 - 提子逻辑和劫争规则实现
开发语言·python·机器学习
意趣新20 小时前
C 语言源文件从编写完成到最终生成可执行文件的完整、详细过程
c语言·开发语言
李艺为21 小时前
根据apk包名动态修改Android品牌与型号
android·开发语言
XXYBMOOO1 天前
内核驱动开发与用户级驱动开发:深度对比与应用场景解析
linux·c++·驱动开发·嵌入式硬件·fpga开发·硬件工程
黄河滴滴1 天前
java系统变卡变慢的原因是什么?从oom的角度分析
java·开发语言
老华带你飞1 天前
农产品销售管理|基于java + vue农产品销售管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot·后端
superman超哥1 天前
Rust Workspace 多项目管理:单体仓库的优雅组织
开发语言·rust·多项目管理·rust workspace·单体仓库
kylezhao20191 天前
C#通过HSLCommunication库操作PLC用法
开发语言·c#