什么是C ++中的bool? [英] What is bool in C++?

查看:364
本文介绍了什么是C ++中的bool?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一些非常有趣的代码,让我想知道bool是什么。我一直认为它是一个原始类型,如int或char或long。但是今天,我看到的东西看起来像这样:

I ran across some very interesting code that makes me wonder about what bool is. I've always considered it to be a primitive type, like int or char or long. But today, I saw something that looked like this:

void boolPtrTest()
{
    bool thisBool = true;

    boolPtrHere(thisBool);

    printf("thisBool is %s\n", thisBool ? "true" : "false");
}

void boolPtrHere(bool& theBool)
{
    theBool = false; // uhh, dereferencing anyone?
}

此代码运行 - 没有错误,并打印thisBool is false!

And this code runs - no errors - and prints "thisBool is false"!

为了进一步使这个奇怪,我运行以下代码:

To further make this odd, I ran the following code:

bool myBool = new bool();

...并且代码运行正常!

...and the code ran fine!

这里是我的问题: bool?它是否按实施的方式定义?从上面的证据,我会说,这是一个类。从实践的角度来看(忽略上面的),将bool定义为int / char的typedef或者使它#define也是合适的。但是,怎么知道它是什么,(这将影响你将如何对待它)?

Here's my question: what is bool? Is it defined on an implementation-by-implementation basis? From the evidence shown above, I would say that it's a class. From a practical standpoint (disregarding the above), it would also seem proper to define a bool as a typedef to an int / char or have it #define'd. But how does one know what it is, (which would affect how you would treat it)?

编辑:我想我会补充说,我在VS工作2008。

I thought I'd add that I'm working in VS 2008.

推荐答案

void boolPtrHere(bool& theBool)
{
    theBool = false; // uhh, dereferencing anyone?
}

此代码没有问题。通过引用获取布尔 。不需要取消引用。

There is nothing wrong with this code. The bool is taken by reference. No dereferencing is required.

bool myBool = new bool();

new 返回地址到 true ,因为它从不返回非零值。这是一个常见的转换,特别是在C代码中:

new returns an address, which is converted to true, since it never returns a nonzero value. This is a common conversion, especially in C code:

int* my_int = malloc(10 * sizeof(int));
if (!my_int) // my_int is converted to bool
    memory_error();

这篇关于什么是C ++中的bool?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆