【发布时间】:2017-03-22 16:39:00
【问题描述】:
为了说明上面的问题,我正在上课学习c++。我们最近刚刚了解了动态数组和类。在最近的一项任务中,我们假设从文本文件中获取信息,并使用给定的结构和类(如下所示)初始化构造函数内动态数组的特定单元格。话虽如此,我的问题是每当我尝试运行程序时它都会崩溃。
class call_record
{
public:
string firstname;
string lastname;
string cell_number;
int relays;
int call_length;
double net_cost;
double tax_rate;
double call_tax;
double total_cost;
};
class call_class
{
public:
call_class();
~call_class();
bool Is_empty();
bool Is_full();
int Search(const string key);
void Add();
void Remove(const string key);
void Double_size();
void Process();
void Print();
private:
int count;
int size;
call_record *call_DB;
};
// default constructor
call_class::call_class()
{
size = 5;
count = 0;
ifstream in;
in.open("callstats_data.txt");
while (!in.eof())
{
if(Is_full())
{
Double_size();
}
in >> call_DB[count].firstname
>> call_DB[count].lastname
>> call_DB[count].cell_number
>> call_DB[count].relays
>> call_DB[count].call_length;
count++;
}
in.close();
}
为了包含更多上下文,我发现这个问题主要出现在我尝试将文件读入类构造函数内部的动态数组时。我尝试使用静态数组而不是动态数组,它完全没有问题;但是,我不能真正使用静态数组。所以我想知道是否有特定的方法可以将文本文件中的信息放入默认构造函数内部的动态数组中。
【问题讨论】:
-
首先:将
call_record *call_DB;改为std::vector<call_record> call_DB;以拥有一个动态数组。 -
您还没有展示您的
Is_full或Double_size方法,问题可能出在其中之一。while (!in.eof())也可能会导致问题,但这些问题可能会表现为不良数据而不是崩溃。 -
第四:您从未为
call_DB分配内存,因此出现了段错误。取消引用未初始化的指针是未定义的行为。
标签: c++ arrays class dynamic default-constructor