No Code(睡觉版) 2018-12-30 23:24 采纳率: 33.3%
浏览 439
已采纳

菜鸟的提问:关于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条回答 默认 最新

  • threenewbee 2018-12-30 15:44
    关注

    如果问题得到解决,请点我回答左上角的采纳和向上的箭头,谢谢

    #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 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题