我在无法正确终止的较大函数中使用此类。
我不得不一次将一个算法注释掉一个算法,以缩小问题开始的位置。
整个过程按编写的方式工作,但最终会因错误终止并终止正在调用它的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;
}
但是除此之外,您所说的“未正确终止”到底是什么意思?
问:您是否有堆栈跟踪/核心转储?
问:您是否已通过调试器逐步执行代码?
问:您是否有特定的错误消息可以复制/粘贴到您的帖子中?