题目要求:
定义一个简单的Computer类,有数据成员芯片(cpu)、内存(ram)、光驱(cdrom)等等,有两个公有成员函数run、stop。cpu为CPU类的一个对象,ram为RAM类的一个对象,cdrom为CDROM类的一个对象,定义并实现这个类,为以上的类编写构造和析构函数,注意使用类组合的思想解决该问题,使得给出的主函数代码可以正确运行并得到给出的输出结果。
坑点:
1.单位GB
2.COMPUTER和CDROM的析构函数的输出是destruct,而CPU和RAM的析构函数输出是desturct
代码实现:
#include <iostream>
using namespace std;
class CPU
{
private:
int rank;
int frequency;
int voltage;
public:
//有参构造函数:
CPU(int i = 1, int j = 2, int k = 100)
{
this->rank = i;
this->frequency = j;
this->voltage = k;
cout << "create a CPU!" << endl;
}
//拷贝构造函数:
CPU(const CPU &p)
{
this->rank = p.rank;
this->frequency = p.frequency;
this->voltage = p.voltage;
cout << "create a CPU by copy!" << endl;
}
~CPU()
{
cout << "desturct a CPU!" << endl;
}
void showinfo()
{
cout << "cpu parameter:" << endl;
cout << "rank:" << rank << endl;
cout << "frequency:" << frequency << endl;
cout << "voltage:" << voltage << endl;
}
};
class RAM
{
private:
int volumn;
public:
RAM(int vol = 1)
{
this->volumn = vol;
cout << "create a RAM!" << endl;
}
RAM(const RAM &r)
{
this->volumn = r.volumn;
cout << "create a RAM by copy!" << endl;
}
~RAM()
{
cout << "desturct a RAM!" << endl;
}
void showinfo()
{
cout << "ram parameter:" << endl;
cout << "volumn:" << volumn << " GB" << endl;
}
};
class CDROM
{
private:
int speed;
public:
CDROM(int c = 16)
{
this->speed = c;
cout << "create a CDROM!" << endl;
}
CDROM(const CDROM &a)
{
this->speed = a.speed;
cout << "create a CDROM by copy!" << endl;
}
~CDROM()
{
cout << "destruct a CDROM!" << endl;
}
void showinfo()
{
cout << "cdrom parameter:" << endl;
cout << "speed:" << speed << endl;
}
};
class COMPUTER
{
private:
CPU cpu;
RAM ram;
CDROM cdrom;
public:
COMPUTER(int r,int f,int v,int l,int s):cpu(r,f,v),ram(l),cdrom(s)
{
cout << "create a COMPUTER with para!" << endl;
}
COMPUTER()
{
cout << "no para to create a COMPUTER!" << endl;
}
COMPUTER(const COMPUTER &p):cpu(p.cpu),ram(p.ram),cdrom(p.cdrom)
{
cout << "create a COMPUTER by copy!" << endl;
}
~COMPUTER()
{
cout << "destruct a COMPUTER!" << endl;
}
void showinfo()
{
cpu.showinfo();
ram.showinfo();
cdrom.showinfo();
}
};
这题真是有病(小声吐槽)(狗头保命)