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 typeX&
,const X&
,volatile X&
orconst 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/