无法调用其他 class C++ 的析构函数
Fail to call destructor of other class C++
所以我有这段代码,当我 运行 它时,当 class B 试图调用它的析构函数时,我得到了 运行 时间错误。 class 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;
}
在B::~B()
中,你在B::array
上调用delete[]
,然后在B::B(const A&)
中通过new
分配它。
这是非法的:您必须始终将 new
与 delete
配对,将 new[]
与 delete[]
配对。
当你不创建元素数组时,你不能使用 delete []
,你的析构函数必须像:
~B(){
delete array;
}
删除 b 中分配的内存时删除 []
,因为您只分配了一个元素,而 []
使编译器假定您正在删除数组分配的内存。
所以我有这段代码,当我 运行 它时,当 class B 试图调用它的析构函数时,我得到了 运行 时间错误。 class 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;
}
在B::~B()
中,你在B::array
上调用delete[]
,然后在B::B(const A&)
中通过new
分配它。
这是非法的:您必须始终将 new
与 delete
配对,将 new[]
与 delete[]
配对。
当你不创建元素数组时,你不能使用 delete []
,你的析构函数必须像:
~B(){
delete array;
}
删除 b 中分配的内存时删除 []
,因为您只分配了一个元素,而 []
使编译器假定您正在删除数组分配的内存。