gpt4 book ai didi

c++ - 为什么我的 "explicit operator bool()"没有被调用?

转载 作者:可可西里 更新时间:2023-11-01 18:15:54 28 4
gpt4 key购买 nike

#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;
}
}

我的期望是 A() 将使用我的 operator bool() 根据上下文转换为 bool,因此打印 是的

但是,输出为 false,表明调用了 operator int()

为什么我的 explicit operator bool 没有按预期调用?

最佳答案

因为 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;
}
}

Live Example打印:“bool:true”并且没有 const 它打印“int:false”

或者,创建一个命名常量:

// operator int() without const

int main()
{
auto const a = A();

if (a)
// as before
}

Live Example打印“bool: true”。

关于c++ - 为什么我的 "explicit operator bool()"没有被调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24489762/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com