2013-01-23 60 views
4

我有简单的例子:C++的默认构造函数未能初始化公共变量?

#include <iostream> 

class parent { 
public: 
    int i; 
}; 

class child : public parent { 
public: 
    int d; 
}; 

int main() { 
    child c; 
    std::cout << c.d << std::endl; 
    return 0; 
} 

If you do not explicitly initialize a base class or member that has constructors by calling a constructor, the compiler automatically initializes the base class or member with a default constructor.

但在C(int d;int i;)所有的整数不会被初始化。

enter image description here

有什么不对呢?或者我没有看到什么obvios?

+0

HTTP:/ /stackoverflow.com/questions/563221/is-there-an-implicit-default-constructor-in-c 看看第一个答案的部分默认的构造函数和POD的注释 – Csq

+1

基本类型don没有建设者。请参阅http://stackoverflow.com/a/5113385/1801919。 –

+0

您提供的链接也适用于Linux编译器,而不是VS2010 –

回答

3

有上没有构造类和基本类型做了默认和零初始化之间的差异:

child c1;   // Default initialized. int types are not initialized. 
child c2 = child(); // Zero initialized. int types are in initialized to zero. 
// In C++ 11 
child c3 {};  // Use new syntax for zero initialization 

更详细的解释:
这里:https://stackoverflow.com/a/7546745/14065
这里:https://stackoverflow.com/a/8280207/14065

4

借助内置的类型,实际上你自己做初始化:

class parent 
{ 
public: 
    parent() : i() {} 
    int i; 
}; 

这将初始化i0

+1

是标准化还是VC++? – us2012

+4

@ us2012标准C++。 – juanchopanza

+0

这被称为_value-initialization_。 – ildjarn

4

内置数据类型(如int)没有真正初始化。他们的“默认构造函数”什么也不做,他们没有默认值。因此,他们只是获得垃圾价值。如果您希望它们具有特定的值,则必须显式初始化内置数据类型。

+0

所以例如对于枚举和所有其他类的简单数据类型(和复杂),我将不得不做什么[juanchopanza](http://stackoverflow.com/a/14490503/1056328)建议? – myWallJSON

+0

@myWallJSON:是的。除了'std :: complex'有一个构造函数,它的成员初始化为零。如果没有一个构造函数正在初始化某个东西(或者明确指定了某个东西),那么它将会有一个垃圾值。 – Cornstalks

相关问题