#include<iostream>
using namespace std;
class A
{
private:
int value;
public:
A(int n)
{
value = n;
}
A(A other) ->改成 A(const A& other)
{
value = other.value;
}
void Print()
{
cout << value << endl;
}
};
int main()
{
A a = 10;
A b = a;
b.Print();
return 0;
}
上面代码中,复制构造函数A(A other)传入的参数是A的一个实例。由于是传值参数,我们把形参复制到实参会调用复制构造函数。因此如果允许复制构造函数传值,就会在复制构造函数内调用复制构造函数,就会形成永无休止的递归调用从而导致栈溢出。因此C++的标准不允许复制构造函数传值参数,在Visual Studio和GCC中,都将编译出错。要解决这个问题,我们可以把构造函数修改为A(const A& other),也就是把传值参数改成常量引用。