2.定义一个简单的Computer类,有数据成员芯片(cpu)、内存(ram)、光驱(cdrom)等等,有两个公有成员函数run、stop。cpu为CPU类的一个对象,ram为RAM类的一个对象,cdrom为CDROM类的一个对象,定义并实现这个类。
#include <iostream> using namespace std; enum CPU_Rank {P1=1,P2,P3,P4,P5,P6,P7 }; class CPU { public: CPU(CPU_Rank newrank=P1,int newfrequency=0,float newvoltage=0.0) :rank(newrank),frequency(newfrequency),voltage(newvoltage) { cout<<"成功构造了一个CPU!"<<endl; cout<<"等级:"<<rank<<endl; cout<<"频率:"<<frequency<<endl; cout<<"电压:" <<voltage<<endl; } void run(); void stop(); ~CPU() { cout<<"成功析构了一个CPU!"<<endl; } private: CPU_Rank rank; int frequency; float voltage; }; inline void CPU::run() { cout<<"cpu运行"<<endl; } inline void CPU::stop() { cout<<"cpu停止"<<endl; } class RAM { public: RAM(int r=0) :ram(r) { cout<<"成功构造一个ram!"<<endl; } ~RAM() { cout<<"成功析构一个ram!"<<endl; } private: int ram; }; class CDRAM { public: CDRAM(int c=0) :cdram(c) { cout<<"成功构造一个cdram!"<<endl; } ~CDRAM() { cout<<"成功析构一个cdram!"<<endl; } private: int cdram; }; class Computer { public: Computer(CPU c,RAM r,CDRAM cd) :cpu(c),ram(r),cdram(cd) { cout<<"成功构造一个computer"<<endl; } void run() { cout<<"computer开始运行"<<endl; } void stop() { cout<<"computer停止运行"<<endl; } ~Computer() { cout<<"析构了一个computer"<<endl; } private: CPU cpu; RAM ram; CDRAM cdram; }; int main() { CPU c(P3,60,220); RAM r(1); CDRAM cd(2); Computer(c,r,cd); return 0; }