Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/126.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为什么我的;显式运算符bool();没打电话? #包括 使用名称空间std; 结构A { 显式运算符bool()常量 { 返回true; } 运算符int() { 返回0; } }; int main() { if(A()) { cout_C++_C++11_Boolean_Type Conversion_Explicit Conversion - Fatal编程技术网

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
}