在C++中,我们使用拷贝构造函数来实现对象的复制。我们需要注意的是,在定义拷贝构造函数的时候,传入参数不能是传值参数,例如A(A other)。因为如果是传值函数,就会在拷贝构造函数内将形参复制为实参,而复制的时候又会调用拷贝构造函数,这样就会造成无休止的递归调用导致栈溢出,因此C++不允许拷贝构造函数传递值参数,最好将拷贝构造函数修改为传递常量引用。
例如:
#include<iostream>
using namespace std;
class A
{
private:
int value;
public:
A(int n)
{
value = n;
}
A(A other)
{
value = other.value;
}
void Paint()
{
cout << value << endl;
}
};
int main()
{
char c;
A a = 10;
A b = a;
b.Paint();
cin >> c;
return 0;
}
这样的拷贝构造函数是无法通过编译的。
#include<iostream>
using namespace std;
class A
{
private:
int value;
public:
A(int n)
{
value = n;
}
A(const A& other)
{
value = other.value;
}
void Paint()
{
cout << value << endl;
}
};
int main()
{
char c;
A a = 10;
A b = a;
b.Paint();
cin >> c;
return 0;
}
这才是正确的写法。