gpt4 book ai didi

C++默认构造函数无法初始化公共(public)变量?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:10:52 24 4
gpt4 key购买 nike

我有一个简单的例子:

#include <iostream>

class parent {
public:
int i;
};

class child : public parent {
public:
int d;
};

int main() {
child c;
std::cout << c.d << std::endl;
return 0;
}

If you do not explicitly initialize a base class or member that has constructors by calling a constructor, the compiler automatically initializes the base class or member with a default constructor.

但 c 中的所有整数(int d;int i;)都没有初始化。

enter image description here

它有什么问题?或者我没有看到明显的东西?

最佳答案

对于内置类型,您实际上必须自己进行初始化:

class parent
{
public:
parent() : i() {}
int i;
};

这会将 i 初始化为 0

关于C++默认构造函数无法初始化公共(public)变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14490476/

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