一个c ++结构有一个默认的构造函数? [英] Does a c++ struct have a default constructor?

查看:171
本文介绍了一个c ++结构有一个默认的构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了以下代码片段:

void foo()
{
    struct _bar_ 
    {
        int a;
    } bar; 

    cout << "Value of a is " << bar.a;
}

并使用g ++ 4.2.1(Mac)编译。输出是a的值为0。

and compiled it with g++ 4.2.1 (Mac). The output is "Value of a is 0".

这是真的说,结构的c ++中的数据成员总是默认初始化(与c相比)?或者是观察到的结果是巧合吗?

Is it true to say that data members of a struct in c++ are always initialized by default (compared to c)? Or is the observed result just coincidence?

我可以想象c ++中的structs有一个默认的构造函数(因为结构和类在c ++中几乎是一样的)将解释为什么bar的数据成员a被初始化为零。

I can imagine that structs in c++ have a default constructor (since a struct and a class is almost the same in c++), which would explain why the data member a of bar is initialized to zero.

推荐答案

简单的答案是肯定的。

它有一个默认构造函数。

The simple answer is yes.
It has a default constructor.

注意:struct和类是相同的(除了访问说明符的默认状态)。

Note: struct and class are identical (apart from the default state of the accesses specifiers).

但是它是否初始化成员取决于实际对象是如何声明的。在您的示例中,没有成员未初始化,并且具有不确定的值。

But whether it initializes the members will depends on how the actual object is declared. In your example no the member is not initialized and a has indeterminate value.

void func()
{
    _bar_  a;                 // Members are NOT initialized.
    _bar_  b = _bar_();       // Members are zero-initialized


    _bar_* aP = new _bar_;    // Members are NOT initialized.
    _bar_* bP = new _bar_();  // Members are zero-initialized
}

// static storage duration objects
//   i.e. objects at the global scope.
_bar_ c; // Members are zero-initialized.

具体细节在标准中解释 8.5 Initializers [dcl.init ] 第4-10段。但下面是对这种情况的一个简单的总结。

The exact details are explained in the standard at 8.5 Initializers [dcl.init] paragraphs 4-10. But the following is a simplistic summary for this situation.

没有用户定义的构造函数的结构有编译器生成的构造函数。但是它的作用取决于它是如何使用的,它将默认初始化其成员(对于POD类型通常是什么)或者它可以零初始化其成员(对于POD通常意味着将其成员设置为零)。

A structure without a user defined constructor has a compiler generated constructor. But what it does depends on how it is used and it will either default initialize its members (which for POD types is usually nothing) or it may zero initialize its members (which for POD usually means set its members to zero).

PS。不要使用 _ 作为类型名称中的第一个字符。你会碰到问题。

PS. Don't use a _ as the first character in a type name. You will bump into problems.

这篇关于一个c ++结构有一个默认的构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆