我正在做一个训练练习,开始上它有麻烦。我必须为数组数据结构编写一个程序。提供了一个测试工具,我需要实现数据结构的代码。我不确定如何在头文件中定义数组
波纹管是我无法编辑的测试线束main.cpp
#include <fstream>
#include <iostream>
using namespace std;
// *****************************
// you need to create this class
// *****************************
#include "ArrayIntStorage.h"
int main(int argc, char **argv) {
// ***********************************
// non-sort read & then sort using std
// ***********************************
ifstream fin1("ACW2_data.txt");
ofstream out1("1-arrayUnsortedRead.txt");
//ofstream out2("2-arrayUnsortedRead-thenSTDSort.txt");
if(!fin1.is_open())
{
cout << "FAIL" << endl;
return 1;
}
ArrayIntStorage arrayStorage1;
arrayStorage1.setReadSort(false); // do not read sort
// read in int values into data structure
fin1 >> arrayStorage1;
// output int values in data structure to file
out1 << arrayStorage1;
// sort data structure using std
arrayStorage1.sortStd();
// output int values in data structure to file
out2 << arrayStorage1;
fin1.close();
out1.close();
out2.close();
头文件的任何信息以及如何与主文件一起使用将不胜感激
梅西·博古
最佳答案
我很确定您应该创建ArrayIntStorage.h header 并实现匹配的ArrayIntStorage.cpp。
基于“使用std排序数据结构”注释,您应该使用它并在适当的STL容器(如std::vector)上创建包装器。
基于“//不读取排序”注释,默认情况下,您应该在每次插入后对 vector 进行排序(当然,除非有人在包装器上调用setReadSort(false))。
除了上述接口(interface)外,您还需要实现>>和<
更新。
在C++ pass variable from .cpp to header file上阅读您的问题,您似乎对这一切感到困惑...
首先,添加对>>和<
您可以通过在.h文件中声明以下运算符来做到这一点:
friend std::ostream& operator<<(std::ostream &out, const ArrayIntStorage &a);
friend std::ifstream & operator>>(std::ifstream &, ArrayIntStorage &);
然后,您可以在.cpp文件中定义其实现:
std::ostream& operator<<(std::ostream &out, const ArrayIntStorage &a)
{ return out; }
std::ifstream & operator>>(std::ifstream &, ArrayIntStorage &)
{ return in; }
显然,您需要在此处添加一些适当的代码,这只是为了使其能够编译。
如果仍然无法编译,请检查您的.h文件中是否包含流头:
#include <fstream>
#include <iostream>
现在获取一些常规信息:
您的数组存储应基于std::vector之类的东西。您需要实现的>>和<
由于ArrayIntStorage是一个类,因此一旦建立了所需的接口(interface)(.h文件中的公共(public)成员函数),则只应查看.h和.cpp即可充实实现。
一旦完成,您将不需要任何“外部”疯狂的回答,也可以回答其他问题。
看一下你的主要功能。如果创建类的对象和fin1流。然后,它将调用您已实现的>>运算符。所有这些都是通过局部变量完成的。
这就是您“使用main.cpp中此变量的值”的方式。您可以使用该变量作为参数来调用类的成员函数。
最后,如果您在理解头文件和链接错误时遇到所有这些问题,您确定您已经开始了正确的培训工作吗?