c++如何初始化对象?下面的情况是这样做两次吗

How does c++ initialize an object? Is the following case doing that twice?

本文关键字:这样做 两次 情况 初始化 对象 c++      更新时间:2023-10-16

假设以下构造函数:

class Needed
{
public: 
    Needed () {}
    Needed (const char *name) {}
};

class Dummy
{
public:
    Dummy (): needed ( "Jimmy" ) {}
private:
    Needed needed;
};

那么,我在这里初始化needed两次了吗?

否您在成员初始化程序列表中只初始化过一次。

否,每个Dummy实例只初始化一次。您刚刚为其初始化提供了参数(并选择了要使用的构造函数)。