C++学习笔记--友元类

本文通过电视和遥控器的关系,介绍了C++中的友元类概念。示例中,遥控器作为友元类可以操作电视的开关状态和频道增减,设定的最大频道数为125。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

生活中简单的电视和遥控器,遥控器既不能继承电视,也不属于组合关系,此时使用友元类,让遥控器可以控制电视。

对例子进行简化,只有电视的开关状态和频道的增加/减少,设置最大频道数125

// tv.h -- Tv and Remote classes
#ifndef TV_H_
#define TV_H_
#include <iostream>
using namespace std;
class Tv
{
public:
    friend class Remote;    // Remote can access Tv private parts
    enum {Off, On};
    Tv(int s = Off, int mc = 125) : state(s), maxchannel(mc),
        channel(2) {}
    void onoff() {state = (state == On) ? Off : On;}
    bool ison() const {return state == On;}
    void chanup();
    void chandown();
private:
    int state;
    int maxchannel;
    int channel;
};
class Remote
{
public:
    Remote() {}
    void onoff(Tv & t) {t.onoff(); cout << "Tv is on/off\n";}
    void chanup(Tv & t) {t.chanup();}
    void chandown(Tv & t) {t.chandown();}
};
#endif
// tv.cpp -- methods for the Tv class (Remote methods are inline
#include <iostream>
#include "tv.h"
using namespace std;
void Tv::chanup()
{
    if (channel < maxchannel)
        channel++;
    else
        channel = 1;
    cout << "Now channel is " << channel << endl;
}
void Tv::chandown()
{
    if (channel > 1)
        channel--;
    else
        channel = maxchannel;
    cout << "Now channel is " << channel << endl;
}
// use_tv.cpp -- using the Tv and Remote classes
#include <iostream>
#include "tv.h"
using namespace std;
int main()
{
    Tv s42;
    s42.onoff();
    Remote grey;
    grey.onoff(s42);
    grey.chanup(s42);
    grey.chanup(s42);
    grey.chandown(s42);
}
输出:

wang@wang:~/c++$ ./a.out
Tv is on/off
Now channel is 3
Now channel is 4
Now channel is 3





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值