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

我的梦境 提交于 2019-12-20 05:45:45

问题


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

    private:
        int num;
};

int main(void)
{
    phone p1(10);

    p1 = 20;    // here!

    return 0;
}

Hi, guys

Just I declared a simple class like above one.
After that I assigned int value to the object that class, then it worked!
(I printed its value. It was stored properly)

If there is not a construct with int parameter, a compile error occurred.
So, I think it's related with a constructor. Is that right?

Please give me a good explanation.
Thanks.


回答1:


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.



来源:https://stackoverflow.com/questions/4766964/how-can-the-assignment-from-int-to-object-be-possible-in-c

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