如何在C ++中从int到对象的赋值是可能的? [英] How can the assignment from int to object be possible 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
只是我声明了一个简单的类,如上面的一个。
之后,我分配int值到该类的对象,然后它工作!
(我打印了它的值。正确存储)
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)
如果没有带int参数的构造,则会发生编译错误。
所以,我认为它与构造函数有关。对不对?
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.
推荐答案
这是合法的,因为C ++解释任何可以用 T
类型的单个参数调用的构造函数作为隐式转换 T
到自定义对象类型。在您的情况下,代码
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;
解释为
p1.operator= (20);
这又解释为
p1.operator= (phone(20));
这种行为真的很奇怪,几乎肯定不是你想要的。要禁用它,可以标记构造函数 explicit
以禁用隐式转换:
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.
这篇关于如何在C ++中从int到对象的赋值是可能的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!