C++ 使用整数强制转换重载代替布尔强制转换重载
我想使用bool cast重载检查某些内容是否有效:C++ 使用整数强制转换重载代替布尔强制转换重载,c++,class,operator-overloading,constants,conversion-operator,C++,Class,Operator Overloading,Constants,Conversion Operator,我想使用bool cast重载检查某些内容是否有效: Menu::operator bool() const { bool empty = false; if (m_title == nullptr) { empty = true; } return empty; } 但是当我使用 if (Menu1) { cout << "valid"; } 似乎对象Menu1不是一个常量对象。因
Menu::operator bool() const {
bool empty = false;
if (m_title == nullptr) {
empty = true;
}
return empty;
}
但是当我使用
if (Menu1) { cout << "valid"; }
似乎对象
Menu1
不是一个常量对象。因此,要将转换运算符调用为bool,需要将其转换为const,而要将转换运算符调用为int,则不需要将其转换为const
将这两个运算符声明为常量成员函数,并使它们(或至少将运算符转换为int)显式
,如下面的演示程序所示:
#include <iostream>
struct A
{
int x = 0;
explicit operator int() const
{
std::cout << "operator int() const is called\n";
return x;
}
explicit operator bool() const
{
std::cout << "operator bool() const is called\n";
return x != 0;
}
};
int main()
{
A a = { 10 };
if ( a ) std::cout << a.x << '\n';
return 0;
}
您尝试的是上下文转换,在这种情况下,您的转换运算符需要格式良好。此特定场景在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 bool\n";
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 << "valid\n";
}
是
Menu1
const
?您可能希望运算符int
也是常量。@ivivjcb Menu1不是常量对象。因此调用int的转换运算符。运算符bool
可以是返回m_title==nullptr代码>或甚至可能重新搜索!m_title
取决于m_title
的类型。虽然奇怪的是,如果它没有m\u title
,它被认为是“有效的”。我们能得到一个静态\u cast
比直接调用操作符bool
更好,例如:如果(静态\u cast(mymenu))
。static\u cast
将调用operator bool
,如果exists@RemyLebeau这也是我的期望。但是静态_cast仍然调用运算符int()。可能是特定于编译器的
operator bool() const is called
10
class Menu
{
int choice;
int mtitle;
public:
Menu(int a, int b):choice(a), mtitle(b){}
operator bool() const {
cout << "Calling op bool\n";
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 << "valid\n";
}
if (mymenu.operator bool())
cout << "Op Bool is called";