Introduction to Programming with c++ 9-2 一个标准的基于对象的入门例子

课本学习

P345页,给了一个关于TV对象的例子。优点:

  • channel, volume两个属性的设置均需要对另外一个属性的基础上。
  • 通过返回值表明,函数执行的成功与否

代码

#include <iostream>

/*
电视频道1-120
声音为1-20
电视默认开机在频道1,声音为0
*/

class TV
{
public:

    TV() : channel_(1), volume_(0), on_(false) {}

    int turn_on()
    {
        on_ = true;
        return 0;
    }
    int turn_off()
    {
        on_ = false;
        return 0;
    }

    int get_channel() const
    {
        return channel_;
    }
    int get_volume() const
    {
        return volume_;
    }


    int set_channel( int channel )
    {
        if( on_ && 1 <= channel && channel <= 120 )
        {   
            channel_ = channel;
            return 0;
        }
        else
            return -1;
    }
    int set_volume( int volume )
    {
        if( on_ && 1 <= volume && volume <= 20 )
        {
            volume_ = volume;
            return 0;
        }
        else
            return -1;
    }

    int channel_up()
    {
        if( on_ && channel_ < 120 )
        {   
            ++channel_;
            return 0;
        }
        else
            return -1;
    }
    int channel_down()
    {
        if( on_ && channel_ > 1 )
        {
            --channel_;
            return 0;
        }
        else
            return -1;
    }

    int volume_up()
    {
        if( on_ && volume_ < 20 )
        {
            ++volume_;
            return 0;
        }
        else
            return -1;
    }
    int volume_down()
    {
        if( on_ && volume_ > 1 )
        {
            --volume_;
            return 0;
        }
        else
            return -1;
    }


private:

    int channel_;
    int volume_;
    bool on_; // state for the tv

};


int main()
{
    TV tv1;
    tv1.turn_on();
    tv1.set_channel(30);
    tv1.set_volume(3);

    TV tv2;
    tv2.turn_on();
    tv2.channel_up();
    tv2.channel_up();
    tv2.volume_up();

    std::cout << "tv1's channel is " << tv1.get_channel() << " and volume is " << tv1.get_volume() << std::endl;
    std::cout << "tv2's channel is " << tv2.get_channel() << " and volume is " << tv2.get_volume() << std::endl;

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值