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?
基础教程推荐
- 这个宏可以转换成函数吗? 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何通过C程序打开命令提示符Cmd 2022-12-09
