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

蓝咒 提交于 2019-12-02 08:57:01

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!