【发布时间】:2017-10-21 20:34:58
【问题描述】:
我正在为一个项目开发数据解析器。我必须解析一个可能包含两种不同类型对象的文件:
类型 1: sb0 硬直线 4 (0, 0) (0, 82) (199, 82) (199, 0)
Type-1 必须存储为类块,具有以下属性:BlockID、BlockType、number_of_edges、lowerleft、lowerright、upperleft、upright。
类型 2: sb1 软矩形 24045 0.300 3.000
Type-2 也必须存储为类块,具有以下属性:BlockID、BlockType、area、min_aspectRatio、max_aspectRatio。
是否可以构建一个名为“block”的类,根据属性“BlockType”使用不同的参数集?我已经构建了一个解析器,但我使用 sstream 为每个 BlockType 使用了两个不同的类。
当要解析的文本文件只包含类型 2 时,我已经展示了解析器的实现。关于如何使用单个类来做到这一点的任何想法?
SoftBlock.h:
#ifndef SOFTBLOCKLIST_H_
#define SOFTBLOCKLIST_H_
#include <string>
#include <vector>
#include "SoftBlock.h"
#include <fstream>
class SoftBlockList {
public:
SoftBlockList(std::string input_file);
std::vector<SoftBlock> get_softblocklist();
private:
std::vector<SoftBlock> softblocklist;
};
#endif /* SOFTBLOCKLIST_H_ */
SoftBlock.cpp:
#include "SoftBlockList.h"
using namespace std;
SoftBlockList::SoftBlockList(string input_file) {
ifstream filehandle;
filehandle.open(input_file.c_str());
string temp;
while(filehandle.good()){
getline(filehandle, temp);
SoftBlock block(temp);
softblocklist.push_back(block);
}
filehandle.close();
}
vector<SoftBlock> SoftBlockList::get_softblocklist(){return
softblocklist;}
【问题讨论】:
-
“类块”是什么意思?请提供一些代码来显示您想要实现的目标。
-
听起来可能是模板的用例。
-
我的意思是一个叫做块的类。我已经编辑了这个问题。基本上,解析器必须将上述两种不同类型的行解析为一个称为“块”的类。但是根据属性“BlockType”,它必须具有不同的属性。
-
上课的目的是什么?它将包含哪些功能?
-
听起来你被要求使用一些继承。您将拥有一个基类(可能是抽象类)和两个专用/依赖类(HardRectilinear 和 SoftRectangular)。当您阅读关键字(是文件的“sb0”部分?或“hardrectilinear”?还是什么?)然后您创建并填充适当的子类。您需要一组指向基类的指针。