所以我有这个代码,当我运行它时,当B类试图调用它的析构函数时,我遇到了运行时错误.A类的析构函数似乎很好.我想知道这段代码有什么问题.谢谢你的帮助.
#include <iostream>
using namespace std;
class A{
public:
//Constructor
A(int N){
this->N = N;
array = new int[N];
}
//Copy Constructor
A(const A& A1){
this->N = A1.N;
//Create new array with exact size
this->array = new int[N];
//Copy element
for(int i=0; i<N; i++){
this->array[i]= A1.array[i];
}
}
~A(){
delete [] array;
cout<<"Success"<<endl;
}
int N;
int* array;
};
class B{
public:
B(const A& array1){
array = new A(array1);
}
~B(){
delete [] array;
}
A* array;
};
using namespace std;
int main(){
A matrix1(10);
B testing(matrix1);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在B::~B(),你叫delete[]上B::array通过其分配后new在B::B(const A&).
这是非法的:你必须始终成对new使用delete,并new[]用delete[].
| 归档时间: |
|
| 查看次数: |
67 次 |
| 最近记录: |