Different cast operator called by different compilers

前端 未结 4 1971
深忆病人
深忆病人 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:24

    Some of the previous answers, already provide a lot of info.

    My contribution is, "cast operations" are compiled similar, to "overloaded operations", I suggest to make a function with a unique identifier for each operation, and later, replace it by the required operator or cast.

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

    And, later, apply the operator or cast.

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

    Just my 2 cents.

提交回复
热议问题