gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:24:34 24 4
gpt4 key购买 nike

我有这个代码:

// 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!

为什么会这样?

最佳答案

它在默认构造 Basehello 成员时调用(在 this->hello = hello; 赋值之前)。

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

Base(const Hello &hello) : hello(hello) { }

关于c++ - 为什么这个构造函数被调用两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43145901/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com