2、定义一个CPU类,包含频率(frequency)、电压(voltage)等私有数据成员, 每个数据成员有两个公有函数用于读写操作。有两个公有的成员函数run、stop表示运行和停止(可用输出信息表示)。其中frequency为整型数的频率值,voltage为浮点型的电压值。写出默认构造函数, 带参数的构造函数,拷贝构造函数,析构函数。 主函数进行测试。
时间: 2023-06-07 11:09:22 浏览: 97
好的,我会按照您的要求回答问题并给出代码示例:
定义一个CPU类如下:
```cpp
class CPU {
private:
int frequency; // 频率值
float voltage; // 电压值
public:
CPU() {
frequency = 0;
voltage = 0.0f;
}
CPU(int f, float v) {
frequency = f;
voltage = v;
}
CPU(const CPU& other) {
frequency = other.frequency;
voltage = other.voltage;
}
~CPU() { }
int getFrequency() const {
return frequency;
}
void setFrequency(int f) {
frequency = f;
}
float getVoltage() const {
return voltage;
}
void setVoltage(float v) {
voltage = v;
}
void run() {
std::cout << "CPU is running.\n";
}
void stop() {
std::cout << "CPU has stopped.\n";
}
};
```
主程序进行测试:
```cpp
int main() {
CPU c1;
c1.setFrequency(2000);
std::cout << "Frequency: " << c1.getFrequency() << std::endl;
c1.setVoltage(1.2f);
std::cout << "Voltage: " << c1.getVoltage() << std::endl;
CPU c2(3000, 1.4f);
std::cout << "Frequency: " << c2.getFrequency() << std::endl;
std::cout << "Voltage: " << c2.getVoltage() << std::endl;
CPU c3(c2);
std::cout << "Frequency: " << c3.getFrequency() << std::endl;
std::cout << "Voltage: " << c3.getVoltage() << std::endl;
c1.run();
c1.stop();
return 0;
}
```
输出结果如下:
```
Frequency: 2000
Voltage: 1.2
Frequency: 3000
Voltage: 1.4
Frequency: 3000
Voltage: 1.4
CPU is running.
CPU has stopped.
```
阅读全文