第二十章 友元类

本文通过具体的代码示例介绍了C++中友元类的使用方法,展示了如何让一个类成为另一个类的友元,从而可以访问其私有成员。同时,文章还涉及了嵌套类的概念。

1.  友元类

#include <iostream>
using namespace std;
class TV 
{
public:
    friend class Tele;            //这样Tele 就可以访问TV类了
    TV():on_off(off),volume(20),channel(3),mode(tv){}
private:    
    enum{on,off};
    enum{tv,av};
    enum{minve,maxve=100};
    enum{mincl,maxcl=60};
    bool on_off;
    int  volume;
    int channel;
    int mode;
};
class Tele
{
public:
    void OnOFF(TV&t){t.on_off=(t.on_off==t.on)?t.off:t.on;}
    void SetMode(TV&t){t.mode=(t.mode==t.tv)?t.av:t.tv;}
    bool VolumeUp(TV&t);
    bool VolumeDown(TV&t);
    bool ChannelUp(TV&t);
    bool ChannelDown(TV&t);
    void show(TV&t)const;    
};
bool Tele::VolumeUp(TV&t)
{
    if (t.volume<t.maxve)
    {
        t.volume++;
        return true;
    } 
    else
    {
        return false;
    }
}
bool Tele::VolumeDown(TV&t)
{
    if (t.volume>t.minve)
    {
        t.volume--;
        return true;
    } 
    else
    {
        return false;
    }
}
bool Tele::ChannelUp(TV&t)
{
    if (t.channel<t.maxcl)
    {
        t.channel++;
        return true;
    } 
    else
    {
        return false;
    }
}
bool Tele::ChannelDown(TV&t)
{
    if (t.channel>t.mincl)
    {
        t.channel--;
        return true;
    } 
    else
    {
        return false;
    }
}
void Tele::show(TV&t)const
{
    if (t.on_off==t.on)
    {
        cout<<"电视现在"<<(t.on_off==t.on?"开启":"关闭")<<endl;
        cout<<"音量大小为:"<<t.volume<<endl;
        cout<<"信号接收模式为:"<<(t.mode==t.av?"AV":"TV")<<endl;
        cout<<"频道为:"<<t.channel<<endl;

    } 
    else
    {
        cout<<"电视现在"<<(t.on_off==t.on?"开启":"关闭")<<endl;
    }

}
int main()
{
    Tele t1;
    TV t2;
    t1.show(t2);
    t1.OnOFF(t2);
    t1.show(t2);
    cout<<"调大声音"<<endl;
    t1.VolumeUp(t2);
    cout<<"频道+1"<<endl;
    t1.ChannelUp(t2);
    cout<<"转换模式"<<endl;
    t1.SetMode(t2);
    t1.show(t2);
    return 0;
}

 

2.  嵌套类

转载于:https://www.cnblogs.com/zenseven/p/3803805.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值