Why is a C++ bool var true by default?(为什么 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 C++ bool var 默认为 true?
基础教程推荐
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
