我很惊讶 thisstruct
只能显式转换为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;
}