C++,不保存其值的类成员数组
c++, class member arrays not holding their value
我有一个名为 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调整大小
此应用程序已请求运行时以异常方式终止。
任何建议不胜感激...
您在构造函数中声明ssplit
和flist
的版本,这些版本隐藏成员变量,因此成员变量永远不会获得分配给它的任何数据。只需从构造函数中删除flist
和ssplit
声明,以便最终将值分配给成员变量。
您在
构造函数中声明的数组是该构造函数的本地数组。你想要的是初始化类的成员数组;只需从构造函数实现中删除std::string flist[9];
和int ssplit[9];
即可。
相关文章:
- 是否可以将结构数组别名为结构成员数组?
- C++:初始化 constexpr 构造函数中的成员数组
- 使用带有参数包的数组的成员数组初始化类
- C++ 在析构函数调用之前删除的动态成员数组
- 初始化在类类型 #define 中定义的非静态成员数组,不带默认 ctor
- 指向具有不同大小的成员数组的指针
- 用另一个 constexpr 数组对成员数组进行大括号初始化
- 对象成员数组C++默认初始化
- 如何在构造函数中的类成员数组中分配数组值,而无需使用STD库
- 将类成员数组组合到单个数组时性能下降
- 如何将数据从公共方法添加到同一类中的私有成员数组中?
- 如何在C 中的派生类中分配数据成员数组
- C 集合构建器中类成员数组的2D数组大小
- 初始化不可复制、不可移动、显式构造类型的成员数组
- C 指针可以指向字符串文字的静态成员数组
- 成员数组位于何处
- 将对象成员数组与字符串进行比较
- 如何在 c++ 中从对象数组中获取数据成员数组
- 声明模板会员参考另一个类的模板成员数组
- C 初始化成员数组