gpt4 book ai didi

c++ - 默认初始化

转载 作者:行者123 更新时间:2023-11-27 23:17:38 25 4
gpt4 key购买 nike

#include <iostream>

using namespace std;
class Apple
{
public:
int i;
string s = "HelloWorld";
string s1;
bool b;
};

int main(int argc, char *argv[]) {
Apple a; //doesn't this trigger default initialization??
cout << a.i << a.s << a.s1 << a.b;

}

如果对象是局部变量,则数据成员将被默认初始化。但这是输出:0HelloWorld0。这不是值初始化吗??

最佳答案

这是一个 simple test这表明您的代码中没有执行任何值初始化。

#include <iostream>
#include <string>

using namespace std;
class Apple
{
public:
int i;
string s = "HelloWorld";
string s1;
bool b;
};

int main()
{
{
Apple a;
a.i = 42;
a.b = true;
cout << a.i << a.s << a.s1 << a.b;
}
{
Apple a;
cout << a.i << a.s << a.s1 << a.b;
}
{
Apple a{};
cout << a.i << a.s << a.s1 << a.b;
}
}

输出:

42HelloWorld142HelloWorld10HelloWorld0

如您所见,在第二种情况下,这些成员仍然包含先前分配的值。请注意,我并不是说这是有保证的或标准定义的行为。

在第三种情况下,您表示应该通过添加大括号对对象进行值初始化。

如果你的编译器不支持C++11的统一初始化语法,可以改成下面这样,也能达到同样的效果。

Apple a = Apple();

关于c++ - 默认初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15465122/

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