【发布时间】:2017-09-19 09:15:27
【问题描述】:
我很惊讶这个 struct,它只能显式转换为 bool,在 if 语句中工作正常:
struct A
{
explicit operator bool( ) const
{
return m_i % 2 == 0;
}
int m_i;
};
int main()
{
A a{ 10 };
if ( a ) // this is considered explicit
{
bool b = a; // this is considered implicit
// and therefore does not compile
}
return 0;
}
为什么会这样? C++ 标准背后的设计原因是什么? 我个人发现第二次转换比第一次更明确。为了更清楚,我希望编译器在这两种情况下都强制具有以下内容:
int main()
{
A a{ 10 };
if ( (bool)a )
{
bool b = (bool)a;
}
return 0;
}
【问题讨论】:
-
是的,
if内部就像是显式转换为 bool。 (你不能比使用if转换为bool更明确!)。 en.cppreference.com/w/cpp/language/explicit
标签: c++11 type-conversion implicit-conversion explicit explicit-conversion