gpt4 book ai didi

c++ - 复制构造函数从 const 转换为非常量?

转载 作者:行者123 更新时间:2023-11-30 01:28:39 25 4
gpt4 key购买 nike

考虑以下几点:

class A
{
public:
int xx;
A(const A& other)
{
cout << "A cctor" << endl;
/* do some stuff */
}

A(int x) : xx(x) {} /* conversion constructor */

};


int main()
{
A a = 1;
A other = a;
return 0;
}

在这种情况下(通常也是如此),说 CCtor 从 const 转换为 non-const 是否正确?

谢谢,罗恩

最佳答案

复制构造函数创建现有对象的新拷贝,该对象可能是也可能不是常量。 A::A(const A& other) 中的 const 只是表示我们不会更改复制构造函数中的 other。事实上,如果您试图在 ctor 内部修改 other,编译器将会对您提示。

创建的对象也可能是也可能不是 const,这取决于您声明它的方式。

关于c++ - 复制构造函数从 const 转换为非常量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7270774/

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