3、定义一个CPU类,包含等级(Rank)、频率(frequency)、电压(voltage)等属性,有两个公有成员函数run、stop。其中,rank为枚举类型CPU__Rank,定义为enum CPU_Rank{P1=1,P2,P3,P4,P5,P6,P7},frequency为单位是MHz的整型数,voltage为浮点型的电压值。观察构造函数和析构函数的调用顺序。
时间: 2023-02-05 17:52:43 浏览: 214
实验4 类与对象
```
enum CPU_Rank { P1 = 1, P2, P3, P4, P5, P6, P7 };
class CPU {
public:
CPU(CPU_Rank rank, int frequency, float voltage)
: rank_(rank), frequency_(frequency), voltage_(voltage) {
std::cout << "Constructor called." << std::endl;
}
~CPU() { std::cout << "Destructor called." << std::endl; }
void run() { std::cout << "Running." << std::endl; }
void stop() { std::cout << "Stopping." << std::endl; }
private:
CPU_Rank rank_;
int frequency_;
float voltage_;
};
```
构造函数会在创建对象时被调用,析构函数会在对象被销毁时被调用。例如:
```
int main() {
CPU cpu(P3, 1000, 1.5); // Constructor called.
cpu.run();
cpu.stop();
return 0; // Destructor called.
}
```
阅读全文