C++ 中 bool 的默认值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/827393/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 17:28:58  来源:igfitidea点击:

Default value for bool in C++

c++boolean

提问by voteblake

I'm redesigning a class constructor in C++ and need it to catch an unspecified bool. I have used default values for all of the other parameters, but from my understanding bool can only be initialized to true or false. Since both of those cases have meaning in the class, how should I handle checking for change from a default value?

我正在用 C++ 重新设计一个类构造函数,需要它来捕获一个未指定的布尔值。我已经为所有其他参数使用了默认值,但根据我的理解,bool 只能初始化为 true 或 false。由于这两种情况在类中都有意义,我应该如何检查默认值的变化?

回答by Steven Canfield

The reality is that you can't do this. A bool has value, either true or false, and if you haven't initialized it then it is randomly true or false, possibly different at each run of the program or allocation of that class.

现实是你不能这样做。bool 有值,要么是真要么是假,如果你还没有初始化它,那么它是随机的真或假,在程序的每次运行或该类的分配时可能不同。

If you need to have a type with more options, define an enum.

如果您需要具有更多选项的类型,请定义一个枚举。

typedef enum MyBool {
    TRUE,
    FALSE,
    FILENOTFOUND
} MyBool;

回答by Daniel Daranas

Tristate bool is the path to the dark side. Tristate bool leads to anger. Anger leads to hate. Hate leads to suffering.

Tristate bool 是通往黑暗面的道路。三态布尔导致愤怒。愤怒导致仇恨。仇恨导致痛苦。



Prefer not to use a tristate bool.

最好不要使用三态布尔值。

Instead, use one additional boolean for whether the first boolean is "initialized" (or better, "known") or not.

相反,使用一个额外的布尔值来判断第一个布尔值是否“初始化”(或者更好,“已知”)。

class Prisoner : public Person
{


  ...

  bool is_veredict_known;
  bool is_guilty;
}

If the veredict is not known yet, you can't tell if the Prisoner is really guilty, but your code can differentiate between the different situations. Of course the Constitution assures that the default value of is_guilty should be false, but, still... :)

如果判决尚不清楚,您无法判断 Prisoner 是否真的有罪,但您的代码可以区分不同的情况。当然,宪法保证 is_guilty 的默认值应该是假的,但是,仍然...... :)

By the way, the class invariant should include:

顺便说一下,类不变量应该包括:

assert(is_veredict_known || !is_guilty);

回答by Josh Kelley

It sounds like you want boost::triboolor maybe boost::optional<bool>.

听起来你想要boost::tribool或者boost::optional<bool>

回答by JaredPar

If that's what you need, create a value which represents the concept of a value that may not have been initialized.

如果这就是您所需要的,请创建一个值来表示可能尚未初始化的值的概念。

template <typename T>
struct Maybe {
  Maybe() : m_hasValue(false) {}
  bool HasValue() const { return m_hasValue; }
  T& Value() { ThrowIfFalse(m_hasValue); return m_value; }
  const T& Value() const { ThrowIfFalse(m_hasValue); return m_value; }
  void SetValue( _In_ const T& value) { m_value = value; m_hasValue = true; }
private:
  bool m_hasValue;
  T m_value;
};

Now you can represent all 3 states you need.

现在您可以表示您需要的所有 3 个状态。

class SomeType { 
  ...
  Maybe<bool> m_myBool;
}

回答by Greg Hewgill

In C++ a boolis only one bit of information, either a 0 or a 1. Since you want to represent three possible states, you need one more bit of information. There are two general techniques:

在 C++ 中,abool只有一位信息,0 或 1。由于您想表示三种可能的状态,因此您还需要一位信息。有两种通用技术:

  1. Use another boolvalue to indicate whether the value is "default" or not, or
  2. Use an enumeration type with three values to indicate (default, true, false).
  1. 使用另一个bool值来指示该值是否为“默认”,或
  2. 使用具有三个值的枚举类型来指示(默认、真、假)。

I would probably choose option 1.

我可能会选择选项 1。

回答by Paul Hilbert

Use the great boost::optional. And not only for bools but for all other places you used some dirty not-initialized-values in. It is used like this:

使用很棒的 boost::optional。不仅对于布尔值,而且对于所有其他地方,您都使用了一些脏的未初始化值。它是这样使用的:

void function(optional<int> value) {
   if (value)
      std::cout << "value is defined: " << value.get() << "\n";
   else
      std::cout << "value is not defined\n";
}

And here's a function example returning an optional:

这是一个返回可选的函数示例:

struct MapClass {
   map<string,int> m_map;

   optional<int> getValue(string key) {
      optional<int> result = none;
      if (m_map.find(key) != m_map.end())
         result = m_map[key];
      return result;
   }
}

回答by VladT

struct Bool { //guaranteed initialized bool
    bool v;

    Bool() : v(false) {}
    operator bool() const { return v; }
    bool& operator=(const bool val){ return v = val; }
};

回答by Laurence Gonsalves

You could have a separate private member that indicates whether the bool value has actually been initialized or not.

您可以有一个单独的私有成员来指示 bool 值是否已实际初始化。

回答by Dan Olson

I don't quite understand, but I'll try...

不是很懂,我试试看。。。

Default values are applied when you have an aggregate initializer that leaves some values unspecified. In that case, bool's default would be false. In a class, the "default" value would be uninitialized, meaning it could be any value and could change from run to run.

当您有一个未指定某些值的聚合初始值设定项时,将应用默认值。在这种情况下,bool 的默认值为 false。在一个类中,“默认”值将是未初始化的,这意味着它可以是任何值,并且可以在每次运行中更改。

If you're interested in whether or not a bool has changed, your best option is to keep track of it with a second bool defaulting to false, or use an enum representing 3 possible states. If you truly want 3 states, you really don't want a bool.

如果您对 bool 是否已更改感兴趣,最好的选择是使用默认为 false 的第二个 bool 来跟踪它,或者使用代表 3 种可能状态的枚举。如果你真的想要 3 个状态,你真的不想要一个布尔值。

回答by Marc Bernier

You really can't. Could you provide a second constructor, for example:

你真的不能。您能否提供第二个构造函数,例如:

class MyClass {
  public:
    MyClass(bool bFlag); // <-- not default
    MyClass(void);       // <-- default
};