c++ - 在私有(private)类语法中复制构造函数

标签 c++ private copy-constructor

2 小时后我将参加 C++ 考试,但我仍然对复制构造函数的语法感到疑惑。

到目前为止,我的理解是您将 CopyConstructor 置于私有(private)状态,这样当某些函数或任何想要复制您的类时,它就不会工作,因为它无法访问私有(private)变量。因此,您可以检查是否遗漏了任何只会生成浅拷贝的指针。

到目前为止一切顺利。

现在我读到的语法是

ClassName(const ClassName &)

我想知道为什么你有那个 & 符号和 const 在那里。仅仅 ClassName(ClassName) 不够吗?

最佳答案

来自 C++14 中的 [class.copy]/2:

A non-template constructor for class X is a copy constructor if its first parameter is of type X&, const X&, volatile X& or const volatile X&, and either there are no other parameters or else all other parameters have default arguments .

因此,根据语言的定义,您的建议不是复制构造函数。

事实上,根据 [class.copy]/6,你的建议是错误的:

A declaration of a constructor for a class X is ill-formed if its first parameter is of type (optionally cv-qualified) X and either there are no other parameters or else all other parameters have default arguments.

关于c++ - 在私有(private)类语法中复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29966658/

相关文章:

c++ - C++11 和 gcc 中的私有(private)和默认构造函数

c++ - 我应该删除运算符赋值函数中的原点指针吗?

c++ - 复制构造函数和动态内存

c++ - 如何为模板嵌套类编写可交换的重载算术运算符?

c++ - 如何使用 x11 中的 xft 字体在窗口中心对齐文本

c++ - 我在这个 C++ 合并排序中做错了什么?

c++ - 以下代码片段是什么意思

c++ - 私有(private)成员的 QT/C++ 类声明对构造函数不可见?

c++ - 模板化构造函数是否覆盖 C++ 中的隐式复制构造函数?

c++ - 从 vc6 dll 创建 wstring 时出现错误指针或链接问题