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

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

问题描述

可能重复:结果
  为什么是一个C ++布尔VAR真正的默认?

说我是做这样的事情:

class blah
{
  public:
  bool exampleVar;
};

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

在exampleArray,现在有设置它们exampleVar 3未设置的情况下,什么是他们的默认值没有我?

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;
};

编辑:

在上面的例子中构造不再需要用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天全站免登陆