表面原因:编译器无法通过,会报如下错误:
error: invalid constructor; you probably meant ‘CExample (const CExample&)’
CExample(CExample ex) //拷贝构造函数
深层次原因是避免拷贝构造函数无限制的递归下去。
栗子:
#include <iostream>
class CExample
{
int m_nTest;
public:
CExample(int x) : m_nTest(x)
{
std::cout << "constructor with argument\n";
}
CExample(const CExample &ex)
{
m_nTest = ex.m_nTest;
std::cout << "copy constructor\n";
}
CExample &operator=(const CExample &ex)
{
std::cout << "assignment operator\n";
m_nTest = ex.m_nTest;
return *this;
}
void myTestFunc(CExample ex)
{
}
};
int main()
{
CExample aaa(2); // 输出:constructor with argument
CExample bbb(3); // 输出:constructor with argument
bbb = aaa; // 输出:assignment operator
CExample ccc = aaa; // 输出:copy constructor
bbb.myTestFunc(aaa); // 输出:copy constructor
return 0;
}
假设拷贝构造函数是传值的,那么在执行如下代码:
CExample ccc = aaa;
会将 aaa 传值到形参,此时构造形参实例时会调用拷贝构造函数,这就造成了无限地构造下去,直至堆栈耗尽,所以为了避免这个问题的发生,直接从编译器的角度禁用了该问题。
参考:拷贝构造函数的参数为什么必须使用引用类型_『小猪呼噜噜』的专栏 -- I Write,therefore I am.-CSDN博客_拷贝构造函数的参数
(SAW:Game Over!)