我有这个代码:
// 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!
为什么会发生这种情况?
它在默认构造hello
成员时调用Base
(在this->hello = hello;
赋值之前)。
使用成员初始化列表来避免这种情况(即hello
直接从参数复制构造成员hello
):
Base(const Hello &hello) : hello(hello) { }
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句