How can the assignment from int to object be possible in C++?

后端 未结 1 1115
[愿得一人]
[愿得一人] 2021-01-21 21:50
class phone {  
    public:  
        phone(int x) { num = x; }
        int number(void) { return num; }
        void number(int x) { num = x; }

    private:
        in         


        
相关标签:
1条回答
  • 2021-01-21 22:40

    This is legal because C++ interprets any constructor that can be called with a single argument of type T as a means of implicitly converting from Ts to the custom object type. In your case, the code

    p1 = 20;
    

    is interpreted as

    p1.operator= (20);
    

    Which is, in turn, interpreted as

    p1.operator= (phone(20));
    

    This behavior is really weird, and it's almost certainly not what you wanted. To disable it, you can mark the constructor explicit to disable the implicit conversion:

    class phone {  
        public:  
            explicit phone(int x) { num = x; }
            int number(void) { return num; }
            void number(int x) { num = x; }
    
        private:
            int num;
    };
    

    Now, the constructor won't be considered when doing implicit conversions, and the above code will cause an error.

    0 讨论(0)
提交回复
热议问题