2017-03-31 140 views
2

我有这样的代码:为什么这个构造函数被调用两次?

// 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; 
} 

的打印结果是:

Hello world! 
Hello world! 

为什么出现这种情况?

+3

这有什么好做移动语义;你的代码中没有任何动作。 –

回答

17

当默认构建Basehello成员(在this->hello = hello;分配之前)时调用它。

使用成员初始化列表,以避免这种情况(即直接从参数hello拷贝构造hello成员):

Base(const Hello &hello) : hello(hello) { } 
相关问题