为什么类型变量;不调用默认的构造函数?
Why does Type variable; does not call the default ctor?
让我们假设以下 class 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.
}
不应该隐式调用默认构造函数吗?
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.
根据 C++ 标准
The implicitly-defined default constructor performs the set of
initializations of the class that would be performed by a user-written
default constructor for that class with no ctor-nitializer (15.6.2)
and an empty compound-statement.
class 有一个普通的默认限制器,它不会初始化 class 的成员。所以他们有不确定的价值。
构造器调用的这种形式
Foo()
值初始化数据成员。对于基本类型,它意味着 zero-initialization.
让我们假设以下 class 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.
}
不应该隐式调用默认构造函数吗?
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.
根据 C++ 标准
The implicitly-defined default constructor performs the set of initializations of the class that would be performed by a user-written default constructor for that class with no ctor-nitializer (15.6.2) and an empty compound-statement.
class 有一个普通的默认限制器,它不会初始化 class 的成员。所以他们有不确定的价值。
构造器调用的这种形式
Foo()
值初始化数据成员。对于基本类型,它意味着 zero-initialization.