Different cast operator called by different compilers

前端 未结 4 1969
深忆病人
深忆病人 2021-02-02 05:15

Consider the following short C++ program:

#include 

class B {
public:
    operator bool() const {
        return false;
    }
};

class B2 : pub         


        
4条回答
  •  清酒与你
    2021-02-02 05:37

    The C++ bool type has two values - true and false with corresponding values 1 and 0. The inherent confusion can be avoided if you add a bool operator in B2 class that calls base class(B)'s bool operator explicitly, then the output comes as false. Here's my modified program. Then operator bool means operator bool and not operator int by any means.

    #include 
    
    class B {
    public:
        operator bool() const {
            return false;
        }
    };
    
    class B2 : public B {
    public:
        operator int() {
            return 5;
        }
        operator bool() {
            return B::operator bool();
        }
    };
    
    int main() {
        B2 b;
        std::cout << std::boolalpha << (bool)b << std::endl;
    }
    

    In your example, (bool) b was trying to call the bool operator for B2, B2 has inherited bool operator, and int operator, by dominance rule, int operator gets called and the inherited bool operator in B2. However, by explicitly having a bool operator in B2 class itself, the problem gets solved.

提交回复
热议问题