无法调用其他类C++的析构函数

Fail to call destructor of other class C++

本文关键字:C++ 析构函数 其他 调用      更新时间:2023-10-16

所以我有这段代码,当我运行它时,当类 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上调用它。

这是非法的:您必须始终将newdelete配对,new[]delete[]配对。

当你不创建元素数组时,你不能使用该delete [],你的析构函数必须像:

~B(){
        delete  array;
    }

删除 b 中分配的内存时删除[],因为您只为一个元素分配了内存,并且[]使编译器假定您正在删除数组分配的内存。