【C++】拷贝构造函数

来源:互联网 发布:海岛奇兵战舰数据 编辑:程序博客网 时间:2024/04/29 03:22
<span style="font-family:Microsoft YaHei;">#include <iostream>using namespace std;class A{private:int value;public:A(int n) { value = n; }A(A other) { value = other.value; }void print() { cout << value; }};int _tmain( int argc, char* argv[]) {A a = 10;A b = a;b.print();return 0;}</span>

这段代码编译出错

..\Class.cpp:15:11: error: invalid constructor; you probably meant 'A (const A&)'
  A(A other) { value = other.value; }
           ^

为什么?

拷贝构造函数A(A other)传入的参数是A的一个实例。

由于是传值参数,我们把形参复制到实参会调用拷贝构造函数。因此如果允许拷贝构造函数传值,就会在拷贝构造函数里调用拷贝构造函数,于是形成无穷无尽的递归调用从而导致栈溢出。因此C++标准不允许拷贝构造函数传值参数,因此将编译出错。

要解决这个问题,要把构造函数改为A(cosnt A&other),也就是把传值参数改为常量引用。


关于拷贝构造函数的更多知识:

http://blog.csdn.net/lwbeyond/article/details/6202256

0 0
原创粉丝点击