这个class'constructor/destructor有问题吗?
Is there a problem with this class' constructor/destructor?
我在未正确终止的较大函数中使用此 class。
我不得不求助于一次一个块地注释掉算法以缩小问题开始的范围。
整个事情都按照写的那样工作,但最终因错误而终止并终止了调用它的 main()
。
无论如何,当我实例化这个 class 时,问题就开始了。我假设它一定是析构函数的问题,当对象超出范围时导致错误。
这是 class 定义以及 constructor/destructor:
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;
}
但除此之外,"isn't terminating properly"到底是什么意思?
问:你有堆栈 trace/core 转储吗?
问:您是否使用调试器单步执行过代码?
问:您是否有特定的错误消息可以 copy/paste 到您的 post 中?
我在未正确终止的较大函数中使用此 class。
我不得不求助于一次一个块地注释掉算法以缩小问题开始的范围。
整个事情都按照写的那样工作,但最终因错误而终止并终止了调用它的 main()
。
无论如何,当我实例化这个 class 时,问题就开始了。我假设它一定是析构函数的问题,当对象超出范围时导致错误。
这是 class 定义以及 constructor/destructor:
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;
}
但除此之外,"isn't terminating properly"到底是什么意思?
问:你有堆栈 trace/core 转储吗?
问:您是否使用调试器单步执行过代码?
问:您是否有特定的错误消息可以 copy/paste 到您的 post 中?