gpt4 book ai didi

c++ - 'true' 并不总是转换为 1

转载 作者:行者123 更新时间:2023-11-30 02:35:05 24 4
gpt4 key购买 nike

我有这个 MFC 代码:

bool SomeBooleanValue;
...
m_ComboBox.ResetContent();
m_ComboBox.AddString("String1");
m_ComboBox.AddString("String2");
m_ComboBox.SetCurSel(SomeBooleanValue);

其中 m_ComboBox 是一个 CComboBox 对象。有时,当 CComboBox::SetCurSel 函数中的 SomeBooleanValue 为真而不是 1 时,我在调试期间看到值 252:

_AFXWIN_INLINE int CComboBox::SetCurSel(int nSelect)// here nSelect = 252!
{ ASSERT(::IsWindow(m_hWnd)); return (int)::SendMessage(m_hWnd, CB_SETCURSEL, nSelect, 0); }

据我所知,C++ 标准说:

An rvalue of type bool can be converted to an rvalue of type int, with false becoming zero and true becoming one.

知道为什么会这样吗?

最佳答案

标准的正确措辞是§ 4.7/p4 Integral conversions [conv.integral]:

If the destination type is bool, see 4.12. If the source type is bool, the value false is converted to zero and the value true is converted to one.

所以是的,异常(exception)的行为是 bool 在其值为 false 时转换为零,在其值为 true 时转换为 1。

同样来自 §3.9.1/p6 基本类型 [basic.fundamental]:

Values of type bool are either true or false.

但注释[49]警告我们:

49) Using a bool value in ways described by this International Standard as “undefined,” such as by examining the value of an uninitialized automatic object, might cause it to behave as if it is neither true nor false.

也就是说,如果您不初始化 boolean 值,则初始值将是未知的(即任意值)。因此,您会得到标准描述为“未定义”的行为。

关于c++ - 'true' 并不总是转换为 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33981801/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com