为什么 C++ bool var 默认为 true? [英] Why is a C++ bool var true by default?

查看:60
本文介绍了为什么 C++ bool var 默认为 true?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

bool "bar" 默认为true,但应该为false,不能在构造函数中初始化.有没有办法在不使其静态的情况下将其初始化为假?

bool "bar" is by default true, but it should be false, it can not be initiliazied in the constructor. is there a way to init it as false without making it static?

简化版代码:

foo.h

class Foo{
 public:
     void Foo();
private:
     bool bar;
}

foo.c

Foo::Foo()
{  
   if(bar)
   {
     doSomethink();
   }
}

推荐答案

其实默认情况下根本没有初始化.你看到的值只是内存中的一些垃圾值用于分配.

In fact, by default it's not initialized at all. The value you see is simply some trash values in the memory that have been used for allocation.

如果你想设置一个默认值,你必须在构造函数中请求它:

If you want to set a default value, you'll have to ask for it in the constructor :

class Foo{
 public:
     Foo() : bar() {} // default bool value == false 
     // OR to be clear:
     Foo() : bar( false ) {} 

     void foo();
private:
     bool bar;
}

更新 C++11:

如果您可以使用 C++11 编译器,您现在可以改为使用默认构造(大部分时间):

If you can use a C++11 compiler, you can now default construct instead (most of the time):

class Foo{
 public:
     // The constructor will be generated automatically, except if you need to write it yourself.
     void foo();
private:
     bool bar = false; // Always false by default at construction, except if you change it manually in a constructor's initializer list.
}

这篇关于为什么 C++ bool var 默认为 true?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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