xml*_*lmx 7 c++ boolean type-conversion explicit-conversion c++11
#include <iostream>
using namespace std;
struct A
{
explicit operator bool() const
{
return true;
}
operator int()
{
return 0;
}
};
int main()
{
if (A())
{
cout << "true" << endl;
}
else
{
cout << "false" << endl;
}
}
Run Code Online (Sandbox Code Playgroud)
我的期望是A()
将在上下文中转换为bool
使用my operator bool()
,因此打印true
.
但是,输出false
显示已operator int()
被调用.
为什么我explicit operator bool
没有按预期召唤?
Tem*_*Rex 16
因为A()
不是const
,所以operator int()
选择了.只需添加const
到其他转换运算符即可:
#include <iostream>
using namespace std;
struct A
{
explicit operator bool() const
{
std::cout << "bool: ";
return true;
}
operator int() const
{
std::cout << "int: ";
return 0;
}
};
int main()
{
if (A())
{
cout << "true" << endl;
}
else
{
cout << "false" << endl;
}
}
Run Code Online (Sandbox Code Playgroud)
打印的实例:"bool:true",没有const
打印"int:false"
或者,创建一个命名常量:
// operator int() without const
int main()
{
auto const a = A();
if (a)
// as before
}
Run Code Online (Sandbox Code Playgroud)
打印"bool:true"的实例.
归档时间: |
|
查看次数: |
1148 次 |
最近记录: |