帮忙改改C++小程序,怎样实现Computer的调用??

来源:百度知道 编辑:UC知道 时间:2024/06/22 00:13:14
#include<iostream>
using namespace std;

class CPU{
private:
int cpu;
public:
CPU(int i){
cpu=i;
cout<<"the kind of cpu is:"<<cpu<<endl;
cout<<"构造了一个CPU"<<endl;}
~CPU(){cout<<"析构了一个CPU"<<endl;}

};

class RAM{
private:
int ram;
public:
RAM(int j){
ram=j;
cout<<"the kind of ram is:"<<ram<<endl;
cout<<"构造了一个RAM"<<endl;}

~RAM(){cout<<"析构了一个RAM"<<endl;}
};

class CDROM{
private:
int cdrom;
public:
CDROM(int k){
cdrom=k;
cout<<"the kind of cdrom is:"<<cdrom<<endl;
cout<<"构造了一个CDROM"<<endl; }
~CDROM(){cout<<"析构了一个CDROM"<<endl;}

};

class Computer{
pri

错误主要在于 Computer 类的构造函数。cpu=i;ram=j;cdrom=k;这三句出现错误,i,j,k是基本数据类型 int,而cpu,ram,cdrom是自定义类的对象,直接赋值造成了类型不匹配。
C++中规定:如果一个类 A 中含有另一个类 B 的对象 b,作为其数据成员。那么该对象 b 的初始化,应该在 A 的构造函数基础上实现。实现如下:
A():b(){}.该题目中 Computer 类的实现,就应该如下:
Computer(int i,int j,int k):cpu(i),ram(j),cdrom(k)
{
cout<<"构造了一个Computer"<<endl;
}

整体程序修改如下:
#include <iostream>
using namespace std;

class CPU
{
private:
int cpu;
public:
CPU(int i)
{
cpu=i;
cout<<"the kind of cpu is:"<<cpu<<endl;
cout<<"构造了一个CPU"<<endl;
}
~CPU(){cout<<"析构了一个CPU"<<endl;}
};

class RAM
{
private:
int ram;
public:
RAM(int j)
{
ram=j;
cout<<"the kind of ram is:"<<ram<<endl;
cout<<"构造了一个RAM"<<endl;
}