正在使用整数强制转换重载,而不是布尔强制转换重载



我想使用bool-cast重载检查某些内容是否有效:

Menu::operator bool() const {
bool empty = false;
if (m_title == nullptr) {
empty = true;
}
return empty;
}

然而,当我使用时

if (Menu1) { cout << "valid"; }

它使用int cast重载而不是

Menu::operator int()
{
int choice = option(); 
return choice;
}
对象Menu1似乎不是一个常量对象。因此,要将转换运算符调用为bool,需要一次转换为const,而要将转换操作符调用为int,则不需要转换为const。

将两个运算符声明为常量成员函数,并使它们(或至少是转换为int的运算符(成为explicit,如下面的演示程序所示:

#include <iostream>
struct A
{
int x = 0;
explicit operator int() const 
{ 
std::cout << "operator int() const is calledn";
return x; 
}
explicit operator bool() const 
{ 
std::cout << "operator bool() const is calledn";
return x != 0; 
}
};
int main() 
{
A a = { 10 };
if ( a ) std::cout << a.x << 'n';
return 0;
}

程序输出为:

operator bool() const is called
10

您正在尝试的是上下文转换,在这种情况下,您的转换运算符需要格式良好。这个具体的场景在cppreference.com题为"上下文转换"的一节中的"隐式转换"下有详细介绍。

事实上,对于上面提到的场景,您所需要做的就是使转换运算符const

以下对我有效:

class Menu
{
int choice;
int mtitle;
public:
Menu(int a, int b):choice(a), mtitle(b){}
operator bool() const {
cout << "Calling op booln";
bool empty = false;
if (mtitle == 1) {
empty = true;
}
return empty;
}
operator int() const
{
cout << "Calling op int"<<"n";
int choice = 2;
return choice;
}    
};
int main()
{    
Menu mymenu(12, 3);
if (mymenu)
cout << "validn";
}

或者,如果您不想对代码进行任何更改,那么在main()中,您可以显式调用运算符,如下所示:

if (mymenu.operator bool())
cout << "Op Bool is called";

最新更新