C ++ bool返回0 1而不是true false

问题描述:

我有重载的equals(包括==和!=),它检查两个对象是否相等,然后返回一个布尔值.

I have overloaded equals (including == and !=) that checks if two objects are equals and then returns a boolean.

不幸的是,它打印0或1.我知道它是正确的,但是我不知道为了可读性而使其打印true或false的方法.

Unfortunately, it prints 0 or 1. I know it's correct but I can't figure out the way to make it to print true or false for readability purposes.

我什至尝试过:

if (a.equals(b))
{
    return true;
}

return false;

但是,C ++固执到足以输出0或1.

However, C++ is stubborn enough to output 0 or 1.

任何帮助将不胜感激.

编辑-完成打印:

cout << "a == b is " << (a == b) << endl;

所需的输出是

a == b是真的

a == b is true

您可以使用 std::boolalpha :

You can use std::boolalpha:

设置str流的boolalpha格式标志.

Sets the boolalpha format flag for the str stream.

设置boolalpha格式标志时,bool值为 作为其名称插入/提取:true和false而不是整数 值.

When the boolalpha format flag is set, bool values are inserted/extracted as their names: true and false instead of integral values.

可以使用noboolalpha机械手取消设置此标志.

This flag can be unset with the noboolalpha manipulator.

初始化时未在标准流中设置boolalpha标志.

The boolalpha flag is not set in standard streams on initialization.

std::cout.setf(std::ios::boolalpha);
std::cout << true;

std::cout << std::boolalpha << true;