不知道是不是下面的复制构造函数有问题?
class A
{
private:
int m;
public:
A(A a){m=a.m}
}
不知道是不是下面的复制构造函数有问题?
class A
{
private:
int m;
public:
A(A a){m=a.m}
}
两件事情:
复制构造函数必须将引用作为参数,否则它们是无限递归的(实际上语言不允许你声明这样的构造函数)
It doesn't do anything the default copy ctor doesn't do, but does it badly - you should use initialisation lists in a copy ctor wherever possible. And if the default copy ctor does what you want, don't be tempted to write a version yourself - you will probably only get it wrong, and you will need to maintain it.
有3个问题。
首先,你忘记了“;” 在 m=am 的末尾,因此您的代码将无法编译。
其次,在大多数情况下,当您传递大小大于平台上寄存器大小的东西时,首选通过引用传递。
第三,由于您不打算更改源对象,因此最好将其与 const 一起使用。所以,最后这就是我们所拥有的:
A(const A & a) : m(am) {}
问题是复制构造函数是为按值传递的参数调用的。因此,如果您不想要非终止递归,则必须通过引用(通常是 const 引用)传递复制构造函数的参数。一个小问题是您没有使用初始化列表,最好是初始化成员。解决这两个问题:
A(A const& a)
: m(a.m)
{}