c++ - 这个类的构造函数/析构函数有问题吗?

标签 c++ class constructor destructor

我在一个更大的函数中使用这个类,它没有正确终止。

我不得不每次将算法注释掉一大块,以缩小问题开始的范围。

整个事情按书面方式工作,但最终以错误方式终止并终止 main()这就是在调用它。

无论如何,当我实例化这个类时,问题就开始了。我假设它一定是析构函数的问题,当对象超出范围时导致错误。

这是类定义以及构造函数/析构函数:

class Entry
{
    private:
        int act_count; //number of activities for generating array MUST BE DETERMINED BEFORE INSTANTIATION
        int ex_count; //number of expenditures for generating array

    public:
        Entry(int, int); // constructor
        ~Entry(); // destructor
        string date; // functions like a title
        Activity * act_arr; // pointer to an array of activities
        Expenditure * ex_arr; // pointer to an array of expenditures 
        // list of member functions
};

struct Activity
{
    public:
        string a_name;
        float time;
};

struct Expenditure
{
    public:
        string e_name;
        float price;
};

构造函数:
Entry::Entry(int a_count, int e_count)
{
    // initialization of basic members
    date = day_o_year();
    act_count = a_count;
    ex_count = e_count;

    // allocation of array space
    act_arr = new Activity[act_count];
    ex_arr = new Expenditure[ex_count];
}

析构函数:
Entry::~Entry()
{
    // prevents memory leaks when object falls out of scope and is destroyed
    delete act_arr;
    delete ex_arr;
}

这里有什么严重的错误吗?我希望这不是太多的代码来引起一些兴趣。

提前致谢。

最佳答案

首先,我认为你需要这个( delete[] 数组):

Entry::~Entry() {
    // prevents memory leaks when object falls out of scope and is destroyed
    delete[] act_arr;
    delete[] ex_arr;
}

但除此之外,“未正确终止”究竟是什么意思?

问:你们有堆栈跟踪/核心转储吗?

问:您是否使用调试器单步调试过代码?

问:您是否有可以复制/粘贴到帖子中的特定错误消息?

关于c++ - 这个类的构造函数/析构函数有问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59314219/

相关文章:

C++ 友元/多态类错误

C++ 使用 Const int 定义数组

Java 构造函数,在哪里放置一次繁重的初始化?

c++ - 类层次结构的内存布局

c++ - OpenGL 可以做到这一点吗?

c++ - 为什么我有一个 '=' 符号输出和 2 个笑脸而不是正确的输出? C++

Java Swing : Access panel components from another class

C++ 多项式加法

c++ - 使用字符串数组作为函数参数

c++ - 内存初始化/删除这么耗时?