Why is a C++ bool var true by default?

前端 未结 7 1737
野趣味
野趣味 2020-12-05 18:51

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?

7条回答
  •  眼角桃花
    2020-12-05 19:51

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

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

提交回复
热议问题