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

2022-01-19 00:00:00 static default boolean c++

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

相关文章