第一次写比较长的面向对象,感觉自己是渣渣……
用到了构造函数,析构函数,类的组合。
#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_Rank getRank() const {return rank;} int getFrequency() const {return frequency;} float getVoltage() const {return voltage;} void setRank(CPU_Rank r) {rank=r;} void setFrequency(int f) {frequency=f;} void setVoltage(float v) {voltage=v;} void run() {cout<<"CPU开始运行!"<<endl;} void stop() {cout<<"CPU停止运行!"<<endl;} }; enum RAM_Type {DDR4,DDR3,DDR2}; class RAM{ private: int volume; int frequency; RAM_Type type; public: RAM (RAM_Type t,int v,int f){ type=t; volume=v; frequency=f; cout<<"构造了一个RAM!"<<endl; } ~RAM() {cout<<"析构了一个RAM!"<<endl;} RAM_Type getType() {return type;} int getVolume() {return volume;} int getFrequency() {return frequency;} void setType(RAM_Type t) {type=t;} void setVolume(int v) {volume=v;} void setFrequency(int f) {frequency=f;} void run() {cout<<"RAM开始运行!"<<endl;} void stop() {cout<<"RAM停止运行!"<<endl;} }; enum CDROM_Interface {SATA,USB}; enum CDROM_Install {external,builtin}; class CDROM{ private: CDROM_Interface interface; CDROM_Install install; int cache; public: CDROM (CDROM_Interface i1, CDROM_Install i2, int c){ interface=i1; install=i2; cache=c; cout<<"构造了一个CDROM!"<<endl; } ~CDROM() {cout<<"析构了一个CDROM!"<<endl;} CDROM_Interface getInterface() {return interface;} CDROM_Install getInstall() {return install;} int getCache() {return cache;} void setInterface(CDROM_Interface i) {interface=i;} void setInstall(CDROM_Install i) {install=i;} void setCache(int c) {cache=c;} void run() {cout<<"CDROM开始运行!"<<endl;} void stop() {cout<<"CDROM停止运行!"<<endl;} }; class COMPUTER{ private: CPU my_cpu; RAM my_ram; CDROM my_cdrom; int storage_size; //GB int bandwidth; //MB public: COMPUTER(CPU c, RAM r, CDROM cd, int s, int b); ~COMPUTER() {cout<<"析构了一个COMPUTER!"<<endl;} void run(){ my_cpu.run(); my_ram.run(); my_cdrom.run(); cout<<"COMPUTER开始运行!"<<endl; } void stop(){ my_cpu.stop(); my_ram.stop(); my_cdrom.stop(); cout<<"COMPUTER停止运行!"<<endl; } }; COMPUTER::COMPUTER(CPU c, RAM r, CDROM cd, int s, int b):my_cpu(c),my_ram(r),my_cdrom(cd){ storage_size=s; bandwidth=b; cout<<"构造了一个COMPUTER!"<<endl; } int main(){ CPU a(P6,300,2.8); a.run(); a.stop(); cout<<"**********"<<endl; RAM b(DDR3,1600,8); b.run(); b.stop(); cout<<"**********"<<endl; CDROM c(SATA,builtin,2); c.run(); c.stop(); cout<<"**********"<<endl; COMPUTER my_computer(a,b,c,128,10); cout<<"**********"<<endl; my_computer.run(); my_computer.stop(); cout<<"**********"<<endl; return 0; }
Computer
时间: 2024-11-09 08:16:00