为什么这个构造函数被调用两次?

jus*_*rld 2 c++ constructor c++11

我有这个代码:

// Example program
#include <iostream>
#include <string>

class Hello{
    public:
    Hello(){std::cout<<"Hello world!"<<std::endl;}
};

class Base{
    public:
    Base(const Hello &hello){ this->hello = hello;}
    private:
    Hello hello;
};

class Derived : public Base{
    public:
    Derived(const Hello &hello) : Base(hello) {}
};

int main()
{
    Hello hello;
    Derived d(hello);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

得到的印刷品是:

Hello world!
Hello world!
Run Code Online (Sandbox Code Playgroud)

为什么会这样?

eml*_*lai 17

默认构造(在赋值之前)的hello成员时调用它.Basethis->hello = hello;

使用成员初始化列表来避免这种情况(即hello直接从参数复制构造成员hello):

Base(const Hello &hello) : hello(hello) { }
Run Code Online (Sandbox Code Playgroud)