先看一段代码:
class A{
int value;
public:
A(int n):value(n){}
A(A other):value(other.value){}
void print(){cout<< value << endl;}
};
上面代码编译报错。
error: invalid constructor; you probably meant `A (const A&)`

A(A other):value(other.value){} => A(const A &other):value(other.value){}
A(A other):value(other.value){}
上面代码是按值传递,实参传递给形参,A other = a; 那么在实参传递给形参的过程中又出现了拷贝构造函数调用,形成递归调用,最终导致内存溢出。
A(const A &other):value(other.value){}
相当于 A &other = a;
代码中定义的构造函数导致了编译错误,因为尝试了按值传递的构造方式,这会引发拷贝构造函数的递归调用,可能造成内存溢出。修正方法是使用引用传递,避免无限递归的问题。

被折叠的 条评论
为什么被折叠?



