作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我遇到了一些看起来像这样的代码:
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/
我是一名优秀的程序员,十分优秀!