大家好,这里是国中之林!
❥前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到网站。有兴趣的可以点点进去看看←
问题:
解答:
main.cpp
#include <iostream>
#include "tv.h"
using namespace std;int main()
{Tv s42;cout << "Initial setting for 42\"TV:\n";s42.setting();s42.onoff();s42.chanup();cout << "\nAdjusted settings for 42\" TV:\n";s42.chanup();cout << "\nAdiusted setting for 42\" TV:\n";s42.setting();Remote grey;grey.set_chan(s42, 10);grey.volup(s42);grey.volup(s42);cout << "\n42\" setting after using remote:\n";s42.setting();Tv s58(Tv::On);s58.set_mode();grey.set_chan(s58, 28);cout << "\n58\" setting:\n";s58.setting();return 0;}
tv.h
#pragma once
#include <iostream>
using namespace std;class Remote;class Tv
{
public:friend class Remote;enum{Off,On};enum{MinVal,MaxVal=20};enum{Antenna,Cable};enum{TV,DVD};Tv(int s = Off, int mc = 125):state(s), volume(5),maxchannel(mc),channel(2),mode(Cable),input(TV){}void onoff() { state = (state == On) ? Off : On; }bool ison()const { return state == On; }bool volup();bool voldown();void chanup();void chandown();void set_mode() { mode = (mode == Antenna) ? Cable : Antenna; }void set_input() { input = (input == TV) ? DVD : TV; }void setting()const;void set_Rmode(Remote& r);private:int state;int volume;int maxchannel;int channel;int mode;int input;
};class Remote
{
public:enum{Normal,InterActive};
private:int mode;int work_mode;
public:friend class Tv;Remote(int m=Tv::TV):mode(m){}bool volup(Tv& t) { return t.volup(); }bool voldown(Tv& t) { return t.voldown(); }void onoff(Tv& t) { t.onoff(); }void chanup(Tv& t) { t.chanup(); }void chandown(Tv& t) { t.chandown(); }void set_chan(Tv& t, int c) { t.channel = c; }void set_mode(Tv& t) { t.set_mode(); }void set_input(Tv& t) { t.set_input(); }int show_mode()const { return work_mode; }
};
tv.cpp
#include "tv.h"bool Tv::volup()
{if (volume < MaxVal){volume++;return true;}else{return false;}
}
bool Tv::voldown()
{if (volume > MinVal){volume--;return true;}else{return false;}
}
void Tv::chanup()
{if (channel < maxchannel){channel++;}else{channel = 1;}
}
void Tv::chandown()
{if (channel > 1){channel--;}else{channel = maxchannel;}
}
void Tv::setting()const
{cout << "TV is " << (state == Off ? "OFF" : "ON") << endl;if (state == On){cout << "Volume setting = " << volume << endl;cout << "Channel setting = " << channel << endl;cout << "Mode = " << (mode == Antenna ? "antenna" : "cable") << endl;cout << "input = " << (input == TV ? "TV" : "DVD") << endl;}
}inline void Tv::set_Rmode(Remote& r)
{r.work_mode = (r.work_mode == Remote::Normal) ? Remote::InterActive : Remote::Normal;
}
运行结果:
考查点:
- 友元类
- 三目运算符
注意:
- 用三目运算符来切换状态
2024年9月11日19:24:56