无法调用其他类C++的析构函数
Fail to call destructor of other class C++
所以我有这段代码,当我运行它时,当类 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;
}
在B::~B()
中,你在B::B(const A&)
中通过new
分配delete[]
后,在B::array
上调用它。
这是非法的:您必须始终将new
与delete
配对,new[]
与delete[]
配对。
当你不创建元素数组时,你不能使用该delete []
,你的析构函数必须像:
~B(){
delete array;
}
删除 b 中分配的内存时删除[]
,因为您只为一个元素分配了内存,并且[]
使编译器假定您正在删除数组分配的内存。
相关文章:
- 什么时候调用组成单元对象的析构函数
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 内联映射初始化的动态atexit析构函数崩溃
- 什么时候调用析构函数
- 优先顺序:智能指针和类析构函数
- C++-明确何时以及如何调用析构函数
- 使用基类指针创建对象时,缺少派生类析构函数
- 在c++中使用向量时,如何调用构造函数和析构函数
- 重载运算符new[]的行为取决于析构函数
- 我需要知道编译器如何在cpp中使用析构函数
- 为什么在使用转换构造函数赋值后调用C++类的析构函数?
- 析构函数调用
- 通过引用传递-为什么要调用这个析构函数
- 对具有动态分配的内存和析构函数的类对象的引用
- 重载 -> shared_ptr 个实例中的箭头运算符<interface>,接口中没有纯虚拟析构函数
- C++成员的析构函数顺序与shared_ptr
- C++ 防止在映射中放置()时调用析构函数
- 在这种情况下显式调用时,std::cout 如何更改析构函数的行为?
- 调用析构函数以释放动态分配的内存
- 不命名构造函数和析构函数上的类型错误