gpt4 book ai didi

c++ - 为什么类型变量;不调用默认的构造函数?

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

<分区>

让我们假设下面的类 Foo。

struct Foo
{
int i;
bool j;
};

为什么我从以下几行中得到不同的结果?

int main(void)
{
//I thought the default constructor would be called
Foo foo1;
cout << foo1.i << " : " << foo1.j << endl; // " 4196352 : 0 " --> ctor not called?

//if calling the default constructor explicitly
foo1 = Foo();
cout << foo1.i << " : " << foo1.j << endl; // " 0 : 0" --> ctor called.
}

难道不应该隐式调用默认构造函数吗?

根据 cpp reference :

If no user-declared constructors of any kind are provided for a class type (struct, class, or union), the compiler will always declare a default constructor as an inline public member of its class.

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