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;
}
相关推荐
cainiao08060512 分钟前
Java 大视界——Java 大数据在智慧交通智能停车诱导系统中的数据融合与实时更新
java·大数据·开发语言
瑞雪兆丰年兮17 分钟前
数学实验(Matlab符号运算)
开发语言·算法·matlab·数学实验
chxii19 分钟前
6.2字节流
java·开发语言
八股文领域大手子36 分钟前
Java死锁排查:线上救火实战指南
java·开发语言·面试
点云SLAM39 分钟前
Python中列表(list)知识详解(2)和注意事项以及应用示例
开发语言·人工智能·python·python学习·数据结果·list数据结果
国强_dev40 分钟前
任意复杂度的 JSON 数据转换为多个结构化的 Pandas DataFrame 表格
开发语言·python
o(╥﹏╥)1 小时前
绑定 SSH key(macos)
开发语言·git·学习·macos
小龙Guo1 小时前
QT+opencv实现卡尺工具找圆、拟合圆
开发语言·qt·opencv
XQ丶YTY1 小时前
大二java第一面小厂(挂)
java·开发语言·笔记·学习·面试
Darkwanderor2 小时前
一般枚举题目合集
c++·算法