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

标签 c++ class constructor default-constructor

<分区>

让我们假设下面的类 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.

最佳答案

根据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.

该类有一个普通的默认限制器,它不会初始化该类的成员。因此它们具有不确定的值。

构造函数调用的这种形式

Foo()

值初始化数据成员。对于基本类型,这意味着零初始化。

关于c++ - 为什么类型变量;不调用默认的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57145870/

相关文章:

C# 在类之间传递数据

javascript - 自定义方法以及构造函数和原型(prototype)在 web-dev 中的用处

c++ - 为什么静态向下转换 unique_ptr 不安全?

c++ - qt gui使用Qfiledialogbox和qlabel显示视频。这是我的代码

php - 从静态方法中创建类实例

C#: 类型名称 <type_name> 在类型 <type> 中不存在;在一个类中,调用另一个类的方法

javascript - Canvas 随重力交替形状

c++ - 使用 shared_from_this 时出现 std::bad_weak_ptr 异常

c++ - 断言语句无法正常运行?

c++ - 为什么可以临时调用成员函数而全局函数不能?