定义并实现一个CPU类。包含等级(rank)、频率(frequency)、电压(voltage)等属性;包含无参构造函数、有参构造函数、复制构造函数、析构函数、公有成员函数run、stop以及和属性对应的公有成员函数set、get。其中ra
时间: 2023-06-14 18:03:54 浏览: 171
nk、frequency、voltage均为私有属性,可以使用set和get函数进行访问和修改。run函数表示CPU运行,stop函数表示CPU停止运行。以下是代码实现:
```c++
class CPU {
private:
int rank;
float frequency;
float voltage;
public:
CPU() : rank(0), frequency(0.0), voltage(0.0) {}
CPU(int r, float f, float v) : rank(r), frequency(f), voltage(v) {}
CPU(const CPU& cpu) : rank(cpu.rank), frequency(cpu.frequency), voltage(cpu.voltage) {}
~CPU() {}
void run() {
cout << "CPU is running." << endl;
}
void stop() {
cout << "CPU has stopped." << endl;
}
void setRank(int r) {
rank = r;
}
void setFrequency(float f) {
frequency = f;
}
void setVoltage(float v) {
voltage = v;
}
int getRank() const {
return rank;
}
float getFrequency() const {
return frequency;
}
float getVoltage() const {
return voltage;
}
};
```
可以使用以下代码进行测试:
```c++
int main() {
CPU cpu(1, 2.5, 1.2);
cout << "Rank: " << cpu.getRank() << endl;
cout << "Frequency: " << cpu.getFrequency() << endl;
cout << "Voltage: " << cpu.getVoltage() << endl;
cpu.setRank(2);
cpu.setFrequency(3.0);
cpu.setVoltage(1.5);
cout << "Rank: " << cpu.getRank() << endl;
cout << "Frequency: " << cpu.getFrequency() << endl;
cout << "Voltage: " << cpu.getVoltage() << endl;
CPU cpu2 = cpu;
cout << "Rank: " << cpu2.getRank() << endl;
cout << "Frequency: " << cpu2.getFrequency() << endl;
cout << "Voltage: " << cpu2.getVoltage() << endl;
cpu.run();
cpu.stop();
return 0;
}
```
阅读全文