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;
}
相关推荐
门前云梦6 小时前
《C语言·源初法典》---C语言基础(上)
c语言·开发语言·学习
achene_ql6 小时前
select、poll、epoll 与 Reactor 模式
linux·服务器·网络·c++
sjtu_cjs7 小时前
Tensorrt python api 10.11.0笔记
开发语言·笔记·python
哆啦A梦的口袋呀7 小时前
深入理解系统:UML类图
开发语言·python·uml
虎冯河7 小时前
怎么让Comfyui导出的图像不包含工作流信息,
开发语言·python
coding随想7 小时前
JavaScript中的原始值包装类型:让基本类型也能“变身”对象
开发语言·javascript·ecmascript
SY师弟7 小时前
51单片机——计分器
c语言·c++·单片机·嵌入式硬件·51单片机·嵌入式
2301_794333917 小时前
Maven 概述、安装、配置、仓库、私服详解
java·开发语言·jvm·开源·maven
葬爱家族小阿杰8 小时前
python执行测试用例,allure报乱码且未成功生成报告
开发语言·python·测试用例