C ++中的未设置布尔的默认值? [英] Default value of an unset boolean in C++?

查看:185
本文介绍了C ++中的未设置布尔的默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

为什么C ++ bool var默认为true?

说我要做这样的事情:

class blah
{
  public:
  bool exampleVar;
};

blah exampleArray[4];
exampleArray[1].exampleVar = true;

在exampleArray中,现在有3个未设置的exampleVar实例,没有我设置它们的默认值?

In exampleArray, there are now 3 unset instances of exampleVar, what are their default values without me setting them?

推荐答案

默认值取决于 exampleArray 如果它是一个函数的局部,值将是随机的,无论这些堆栈位置发生在什么值。如果它是静态的或在文件范围(全局)中声明,则值将初始化为零。

The default value depends on the scope that exampleArray is declared in. If it is local to a function the values will be random, whatever values those stack locations happened to be at. If it is static or declared at file scope (global) the values will be zero initialized.

这里是一个示范。如果你需要一个成员变量有一个确定的值总是在构造函数中初始化它。

Here's a demonstration. If you need a member variable to have a deterministic value always initialize it in the constructor.

class blah
{
  public:
  blah() 
  : exampleVar(false)
  {}

  bool exampleVar;
};

EDIT:上面的例子不再需要与C ++ 11。数据成员可以在类声明中初始化。


The constructor in the above example is no longer necessary with C++11. Data members can be initialized within the class declaration itself.

class blah
{
  public:
  bool exampleVar = false;
};

如果需要,此内联默认值可以由用户定义的构造函数覆盖。

This inline default value can be overridden by a user-defined constructor if desired.

这篇关于C ++中的未设置布尔的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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