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

阅读 97

2022-01-27

#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)

0 0 举报