C++ 为什么我的;显式运算符bool();没打电话? #包括 使用名称空间std; 结构A { 显式运算符bool()常量 { 返回true; } 运算符int() { 返回0; } }; int main() { if(A()) { cout
因为C++ 为什么我的;显式运算符bool();没打电话? #包括 使用名称空间std; 结构A { 显式运算符bool()常量 { 返回true; } 运算符int() { 返回0; } }; int main() { if(A()) { cout,c++,c++11,boolean,type-conversion,explicit-conversion,C++,C++11,Boolean,Type Conversion,Explicit Conversion,因为A()不是const,所以选择了运算符int()。只需将const添加到另一个转换运算符,它就可以工作: #include <iostream> using namespace std; struct A { explicit operator bool() const { return true; } operator int() { return 0; } }; int main() {
A()
不是const
,所以选择了运算符int()
。只需将const
添加到另一个转换运算符,它就可以工作:
#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;
}
}
打印“bool:true”。我希望输出为true。但是,实际输出为
false
,而不是true
!请澄清您的问题。@xmlmx您没有详细说明任何内容。@downvoter:请详细说明,以便我可以改进我的anwswer!还有第三种选择(尽管我不推荐),这将提供一个非常量重载运算符bool()
。
#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;
}
}
// operator int() without const
int main()
{
auto const a = A();
if (a)
// as before
}