大!大萝卜! 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;
    }
    评论

报告相同问题?

悬赏问题

  • ¥20 关于#windows#的问题,请各位专家解答!(相关搜索:服务器)
  • ¥30 使用C++实现ATM系统
  • ¥20 求帮,直连能连上oracle12,但是thinkphp6就是报错
  • ¥15 paddleocr运行报错
  • ¥15 怎么用 matlab 设计滞后-超前串联校正网络
  • ¥15 MFC引用C#生成的dll,将dll放置到非exe程序目录,如何操作
  • ¥15 C#创建webservice接口,三方通过多次跳转访问本方服务,获取wsdl文档,wsdl中ip地址为局域网内本机地址而非三方直接访问的地址。
  • ¥15 关于#wireshark#的问题:需要安卓app流量数据集要安卓流量做包序列长度的实验,比如某些流量是在看视频还是在发评论
  • ¥15 Smail语句如何使用判断语句跳过验证卡密界面
  • ¥15 关于#wireshark#的问题:并且能够给数据做标注,如这个流量是在看视频或者是在转账