设计一个电视机类。成员变量包括商品编号、商品型号、生产厂家、大小、重量、开关状态 等, 同时设计一些方法对电视机的状态进行控制。例如,方法应包括开/关电视机、更换频 道、提高/减小音量等。要求商品编号自动生成。注意:有些成员变量应定义成静态的(static), 控制和操纵静态成员变量的方法应是静态的(static)。
时间: 2023-05-30 15:01:56 浏览: 77
class TV {
private:
static int count; // 商品编号计数器
int id; // 商品编号
string model; // 商品型号
string manufacturer; // 生产厂家
int size; // 大小,单位:英寸
float weight; // 重量,单位:千克
bool powerOn; // 开关状态,true 表示打开,false 表示关闭
int channel; // 当前频道
int volume; // 当前音量
public:
TV(string model, string manufacturer, int size, float weight) {
this->id = ++count;
this->model = model;
this->manufacturer = manufacturer;
this->size = size;
this->weight = weight;
this->powerOn = false;
this->channel = 1;
this->volume = 50;
}
void powerSwitch() {
powerOn = !powerOn;
if (powerOn) {
cout << "电视机已经打开" << endl;
} else {
cout << "电视机已经关闭" << endl;
}
}
void setChannel(int channel) {
this->channel = channel;
cout << "已切换到" << channel << "频道" << endl;
}
void increaseVolume() {
if (volume < 100) {
volume++;
cout << "音量已提高,当前为:" << volume << endl;
} else {
cout << "音量已经最大了,不能再提高了" << endl;
}
}
void decreaseVolume() {
if (volume > 0) {
volume--;
cout << "音量已降低,当前为:" << volume << endl;
} else {
cout << "音量已经最小了,不能再降低了" << endl;
}
}
static int getCount() {
return count;
}
static void resetCount() {
count = 0;
}
};
int TV::count = 0; // 初始化计数器
int main() {
TV tv("ABC123", "Sony", 50, 20.5);
cout << "当前商品编号为:" << tv.getCount() << endl;
tv.powerSwitch();
tv.setChannel(5);
tv.increaseVolume();
tv.increaseVolume();
tv.decreaseVolume();
TV::resetCount(); // 重置计数器
return 0;
}