gpt4 book ai didi

c++ - 从 int 到类类型的隐式转换

转载 作者:行者123 更新时间:2023-11-28 05:44:09 31 4
gpt4 key购买 nike

我遇到了一些看起来像这样的代码:

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

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

为什么可以从 int 类型转换为 Cents 类类型?另外,这种情况下是否调用了复制构造函数?

最佳答案

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

它是允许的,因为它有时很方便。但这也可能有问题:这就是为什么您可以通过使类构造函数显式来禁止此类隐式构造。

Also, is the copy constructor called in this case?

因为它是一个右值,调用将是一个移动构造函数/赋值(它可以回退到一个复制构造函数/赋值);但编译器可能会忽略它。如果您明确地写下,它将等同于:

Cents c = Cents(0); 

关于c++ - 从 int 到类类型的隐式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36557340/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com