implicit conversions from and to class types

后端 未结 2 1360
说谎
说谎 2020-12-28 22:20

I am studying converting constructors and conversion operators in C++. What I\'ve learned so far is that any non-explicit constructor that takes only one parameter (and any

2条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-28 23:12

    This is something you can easily try and see what the compiler does:

    #include 
    
    struct ABC {
        int v;
        ABC(int x) : v(x) { }
        operator int() const { return v; }
        void operator +=(ABC const &that) {
            v += that.v;
        }
    };
    
    ABC operator+(ABC const &lhs, ABC const &rhs) {
        return { lhs.v + rhs.v };
    }
    
    int main() {
        ABC a(5);
        std::cout << a + 1 << '\n';
        a += 10;
        std::cout << a << '\n';
    }
    

    what if I defined an overloaded + operator to take two class_type objects as its arguments?

    GCC

    error: ambiguous overload for 'operator+' (operand types are 'ABC' and 'int')

    The compiler sees two candidates: operator+(int, int) and ABC operator+(const ABC&, const ABC&). This means it could implicitly convert not only the 5 in a + 5 to a but also the a to int. Post these conversions both operator+ functions become potential matches.

    How is the compiler supposed to know which one to call through function matching?

    It doesn't know hence the error.

    does the conversion to int only happens implicitly when only the built-in operator is defined?

    Yes, otherwise it doesn't automatically convert class_type to int. However, int to class_type would happen implicitly unless you make class_type's constructor explicit:

    explicit ABC(int x) : v(x) { }
    

    If you've access to C++11, then you also make the conversion function explicit:

    explicit operator int() const { return v; }
    

提交回复
热议问题