How can I assign an int object to an object in C ++?

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

I just declared a simple class, as above.
After that, I assigned an int value to an object of this class, then it will work!
(I typed its value. It was saved correctly)

If there is no construct with the int parameter, a compilation error has occurred.
So, I think this is due to the constructor. Is it correct?

Please give me a good explanation.
Thanks.

0
c ++ variable-assignment assignment-operator constructor
source share
1 answer

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 T to the type of a custom object. In your case, the code

 p1 = 20; 

interpreted as

 p1.operator= (20); 

Which, in turn, is 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 flag the explicit constructor 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 will not be taken into account when performing implicit conversions, and the above code will cause an error.

+6
source share

All Articles