使用整数转换重载而不是 bool 转换重载

ivi*_*jcb 4 c++ class constants operator-overloading conversion-operator

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

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

        return empty;
    }
Run Code Online (Sandbox Code Playgroud)

但是当我使用

if (Menu1) { cout << "valid"; }
Run Code Online (Sandbox Code Playgroud)

它使用 int cast 重载代替

Menu::operator int()
    {
        int choice = option(); 
        return choice;
    }
Run Code Online (Sandbox Code Playgroud)

Vla*_*cow 6

似乎对象Menu1不是常量对象。所以调用转换运算符到bool,需要一次转换成const,而调用转换运算符到int,不需要转换成const。

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

#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;
}
Run Code Online (Sandbox Code Playgroud)

程序输出为:

operator bool() const is called
10
Run Code Online (Sandbox Code Playgroud)