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?
基础教程推荐
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- c++ STL设置差异 2022-01-01
