大!大萝卜! 2020-11-18 18:17 采纳率: 0%
浏览 15

菜鸟的提问:关于C++类的组合的疑问,我这串代码哪儿错了

#include
using namespace std;
class CPU
{
CPU(int c=1);
};
class RAM
{
RAM(int ram=2);
};
class CDROM
{
CDROM(int cdrom=3);
};
class Computer
{
public:
Computer(CPU c,RAM r,CDROM d);
~Computer();
void run()
{
cout<<"cpu为:"<<cpu<<" "<<"ram为:"<<ram<<" "<<"cdrom为:"<<cdrom<<endl;
cout<<"调用的是这个run函数"<<endl;
}
void stop()
{
cout<<"调用的是这个stop函数"<<endl;
}
private:
CPU cpu;
RAM ram;
CDROM cdrom;
};
Computer::Computer(CPU c,RAM r,CDROM d):cpu(c),ram(r),cdrom(d)
{
cout<<"调用的是构造函数"<<endl;
}
Computer::~Computer()
{
cout<<"调用的是该析构函数"<<endl;
}
int main()
{
Computer thing();
thing.run();
thing.stop();
return 0;
}
  • 写回答

1条回答 默认 最新

  • flybirding10011 测试 2020-11-18 18:49
    关注
    #include <iostream>
    
    using namespace std;
    
    class CPU
    {
    private:
        int val;
    public:
        CPU(int c = 1) { val = c; }
        friend ostream& operator << (ostream& output, CPU& c)
        {
            output << "CPU" << c.val;
            return output;
        }
    };
    class RAM
    {
    private:
        int val;
    public:
        RAM(int ram = 2) { val = ram; }
        friend ostream& operator << (ostream& output, RAM& r)
        {
            output << "RAM" << r.val;
            return output;
        }
    };
    class CDROM
    {
    private:
        int val;
    public:
        CDROM(int cdrom = 3) { val = cdrom; }
        friend ostream& operator << (ostream& output, CDROM& c)
        {
            output << "CDROM" << c.val;
            return output;
        }
    };
    class Computer
    {
    public:
        Computer(CPU c, RAM r, CDROM d);
        ~Computer();
        void run()
        {
            cout << "cpu为:" << cpu << " " << "ram为:" << ram << " " << "cdrom为:" << cdrom << endl;
            cout << "调用的是这个run函数" << endl;
        }
        void stop()
        {
            cout << "调用的是这个stop函数" << endl;
        }
    private:
        CPU cpu;
        RAM ram;
        CDROM cdrom;
    };
    Computer::Computer(CPU c, RAM r, CDROM d) :cpu(c), ram(r), cdrom(d)
    {
        cout << "调用的是构造函数" << endl;
    }
    Computer::~Computer()
    {
        cout << "调用的是该析构函数" << endl;
    }
    int main()
    {
        CPU c;
        RAM r;
        CDROM cd;
        Computer thing(c, r, cd);
        thing.run();
        thing.stop();
        return 0;
    }
    评论

报告相同问题?

悬赏问题

  • ¥15 YOLOv8已有一个初步的检测模型,想利用这个模型对新的图片进行自动标注,生成labellmg可以识别的数据,再手动修改。如何操作?
  • ¥15 怎么做商品窗体,完完全全不会
  • ¥30 NIRfast软件使用指导
  • ¥20 matlab仿真问题,求功率谱密度
  • ¥15 求micropython modbus-RTU 从机的代码或库?
  • ¥15 铜与钢双金属板叠加在一起每种材料300mm长,18mm宽,4mm厚一端固定并加热至80℃,当加热端温度保持不变时另一端的稳态温度。ansys
  • ¥15 django5安装失败
  • ¥15 Java与Hbase相关问题
  • ¥15 后缀 crn 游戏文件提取资源
  • ¥20 bash代码推送不上去 git fetch origin master #失败了