我有一个问题,如何避免类里面的破坏。 我这里有 C++ 示例代码:
class Array {
int *p;
int n;
public:
Array(int n_ = 0) {
p = new int[n_];
}
~Array(void) {
cout << "Deleted" << endl; delete []p;
}
friend Array operator+(Array A, Array B) // the amount of elements A and B are the same
{
Array S(A.n);
for(int i=0; i < A.n; i++)
S.p[i] = A.p[i] + B.p[i];
return S; // object S has been destroyed before returned.
}
};
在这里,当对象获得值并返回时。但对象S在返回之前已经被销毁了。任何人都可以帮助我避免破坏或者可以通过某种方式将对象 S 返回到 main.谢谢
最佳答案
您可以定义移动和/或复制构造函数(如果未隐式定义),并且该值将在销毁之前移动/复制。
关于c++ - 如何避免类里面的破坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29893126/