问题
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 T
s 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