C++,不保存其值的类成员数组

c++, class member arrays not holding their value

本文关键字:成员 数组 保存 C++      更新时间:2023-10-16

我有一个名为 opf 的类,它包含两个在构造函数中初始化的数组。在主代码中,我创建了一个名为curfile的opf实例,并运行其成员函数testfunc()。变量 fnum 可以很好地携带其值来测试func,但是当我调用数组的成员 ssplit 时,我得到了巨大的整数,并且我无法调用 flist 的成员而不会向我抛出运行时错误。

//in main.cpp
int main()
{
   opf curfile;
   curfile.testfunc();
}
//in opf.h
class opf
{
private:
   std::string defpath;
   bool initf;
public:
   opf();
   ~opf();
   std::string flist[9];
   int ssplit[9];
   int fnum;
   std::string path; //path including filename
      std::string filename; //just the filename
   std::vector<std::vector<std::string> > etoken; //(0, std::vector<std::string>(fnum))//all entries  in file
   std::ifstream instream; //read stream
   std::ofstream outstream; //write stream
   bool oread(std::string NIC, std::string year, std::string month);
   void dcache();
   void testfunc();
};
//in opf.c
    opf::opf()
{
   std::string flist[9];
   flist[0] = "Year"; flist[1] = "Month"; flist[2] = "Date";
   flist[3] = "Hour"; flist[4] = "Cell/Subject"; flist[5] = "Issue";
   flist[6] = "Status"; flist[7] = "Comments"; flist[8] = "Completion Date";
   fnum = sizeof(flist)/sizeof(*flist);
   defpath = "\\*****************\User\TaskTracker\";
   int ssplit[9];
   ssplit[0] = 4; ssplit[1] = 12; ssplit[2] = 18;
   ssplit[3] = 24; ssplit[4] = 40; ssplit[5] = 80;
   ssplit[6] = 120; ssplit[7] = 145; ssplit[8] = 160;
   initf = true;
   }
opf::~opf(){}
void opf::testfunc()
{
   for(int i = 0; i < 9; i++)
   {
      std::cout << ssplit[i] << " ";
      std::cout << flist[i] << " ";
   }
   return;
}

Testfunc 打印以下内容:

1853187679 2621539 2002153829 57503856 -2 2001877146 2001876114 0 8558496 在抛出"std::length_error"实例后调用终止what(): basic_string调整大小

此应用程序已请求运行时以异常方式终止。

任何建议不胜感激...

您在构造函数中声明ssplitflist的版本,这些版本隐藏成员变量,因此成员变量永远不会获得分配给它的任何数据。只需从构造函数中删除flistssplit声明,以便最终将值分配给成员变量。

您在

构造函数中声明的数组是该构造函数的本地数组。你想要的是初始化类的成员数组;只需从构造函数实现中删除std::string flist[9];int ssplit[9];即可。