題目
定義一個簡單的Computer類,有數據成員芯片(cpu)、內存(ram)、光驅(cdrom)等等,有兩個公有成員函數run、stop。cpu爲CPU類的一個對象,ram爲RAM類的一個對象,cdrom爲CDROM類的一個對象,定義並實現這個類。
AC的C++代碼如下:
#include <iostream>
using namespace std;
enum CPU_rank {P1=1,P2,P3,P4,P5,P6,P7};
class CPU
{
private:
CPU_rank rank;
int frequency;
float voltage;
public:
CPU (CPU_rank r, int f, float v)
{
rank = r;
frequency = f;
voltage = v;
cout << "構造了一個CPU!" << endl;
}
CPU() { cout << "構造了一個CPU!" << endl; };
~CPU () { cout << "析構了一個CPU!" << endl; }
void Run() {cout << "CPU開始運行!" << endl; }
void Stop() {cout << "CPU停止運行!" << endl; }
};
class RAM
{
public:
RAM () { cout << "構造了一個RAM!" << endl; }
~RAM (){ cout << "析構了一個RAM!" << endl; }
void Run() {cout << "RAM開始運行!" << endl; }
void Stop() {cout << "RAM停止運行!" << endl; }
};
class CDROM
{
public:
CDROM (){ cout << "構造了一個CDROM!" << endl; }
~CDROM () { cout << "析構了一個CDROM!" << endl; }
void Run() {cout << "CDROM開始運行!" << endl; }
void Stop() {cout << "CDROM停止運行!" << endl; }
};
class computer
{
private:
CPU cpu;
RAM ram;
CDROM cdrom;
public:
computer() {cout << "構造了一個computer!" << endl; }
~computer () { cout << "析構了一個computer!" << endl; }
void Run()
{
cout << "computer開始運行!" << endl;
cpu.Run();
ram.Run();
}
void Stop()
{ ram.Stop();
cpu.Stop();
cout << "computer停止運行!" << endl;
}
};
int main()
{
computer a;
a.Run();
a.Stop();
return 0;
}