gpt4 book ai didi

c++ - 如何避免类中的破坏

转载 作者:搜寻专家 更新时间:2023-10-31 02:22:51 24 4
gpt4 key购买 nike

<分区>

我有一个问题,我怎样才能避免类里面的破坏。我这里有示例代码 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 的某种方式。谢谢

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com