从 int 到 class 类型的隐式转换

Implicit conversion from int to a class type

我 运行 浏览了一些看起来像这样的代码:

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

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

为什么可以从 int 类型转换为 class Cents 类型?还有,这种情况下是不是调用了拷贝构造函数?

Why is it possible to convert from int to type of class Cents?

它是允许的,因为它有时很方便。但它也可能有问题:这就是为什么你可以通过使 class 构造函数 explicit.

来禁止这种隐式构造

Also, is the copy constructor called in this case?

因为它是一个右值,所以调用将是移动 constructor/assignment(这可能回退到副本 ctor/assignment);但编译器可能会忽略它。如果你明确地写了,它将等同于:

Cents c = Cents(0);