简体   繁体   English

从int隐式转换为类类型

[英]Implicit conversion from int to a class type

I ran across some code that looked like this: 我遇到了一些看起来像这样的代码:

class Cents
{
private:
    int m_nCents;
public:
    Cents(int nCents) : m_nCents(nCents)
    {
    }
 };

int main(){
    Cents c = 0; // why is this possible?
}

Why is it possible to convert from int to type of class Cents? 为什么可以从int转换为Class Cents类型? Also, is the copy constructor called in this case? 另外,在这种情况下是否调用了复制构造函数?

Why is it possible to convert from int to type of class Cents? 为什么可以从int转换为Class Cents类型?

It is allowed because it's handy sometimes. 允许使用,因为它有时很方便。 But it may also be problematic: that's why you can forbid such implicit constructions by making the class constructor explicit . 但这也可能是有问题的:这就是为什么您可以通过将类构造函数设为explicit来禁止这种隐式构造。

Also, is the copy constructor called in this case? 另外,在这种情况下是否调用了复制构造函数?

Since it's an rvalue, the call would be to a move constructor/assignment (which could fallback to a copy ctor/assignment); 由于它是一个右值,因此将调用到移动构造函数/赋值(可能会回退到副本ctor /赋值); but the compiler will likely omit that. 但是编译器可能会忽略这一点。 If you wrote that explicitly, it would be equivalent to: 如果您明确地编写该代码,则相当于:

Cents c = Cents(0); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM