C++标准不允许拷贝(复制)构造函数传值参数,而必须是传引用或者是常量引用;传值参数在Visual Studio/GCC中都会编译出错。
编译下面的代码:
#include <iostream>
using namespace std;
class Test
{
public:
Test()
{
cout<<"Default Constructor"<<endl;
}
Test(Test other) // Test(const Test& other)
{
cout<<"Copy Constructor"<<endl;
}
};
int main()
{
Test test;
Test testCopy = test;
return 0;
}
将会导致编译错误;
如果拷贝构造函数使用的是传值参数,由于是传值,在把实参拷贝到形参时会调用拷贝构造函数,这将会导致永无休止的递归并造成栈溢出。