0
点赞
收藏
分享

微信扫一扫

C++中如何在一个类中初始化其它类

小北的爹 2022-01-27 阅读 96
c++
#include <iostream>

using namespace std;

class GPU {
public:
    GPU(int id) : m_gpuId(id)
    {
        cout << "GPU" << endl;
    }
private:
    int m_gpuId;
};

class Memory {
public:
    Memory(int mem) : m_memSize(mem)
    {
        cout << "Memory" << endl;
    }
private:
    int m_memSize;
};

class DeviceManager {
public:
    DeviceManager()
    {
        cout << "DeviceManager" << endl;
    }
private:
    GPU m_gpu{2};
    Memory m_memory{3};
};

int main()
{
    DeviceManager deviceManager;
    return 0;
}

执行结果

GPU
Memory
DeviceManager

假如改用指针,则不会创建其它对象的实例,见下面的代码

#include <iostream>

using namespace std;

class GPU {
public:
    GPU(int id) : m_gpuId(id)
    {
        cout << "GPU" << endl;
    }
private:
    int m_gpuId;
};

class Memory {
public:
    Memory(int mem) : m_memSize(mem)
    {
        cout << "Memory" << endl;
    }
private:
    int m_memSize;
};

class DeviceManager {
public:
    DeviceManager()
    {
        cout << "DeviceManager" << endl;
    }
private:
    GPU *m_gpu;
    Memory *m_memory;
};

int main()
{
    DeviceManager deviceManager;
    return 0;
}

运行结果

DeviceManager
举报

相关推荐

0 条评论