2017-10-21 57 views
-1

我正在为一个项目数据解析器工作的类。我要解析可以包含两种不同类型的对象的文件:实现不同的参数集

类型-1: SB0 hardrectilinear 4(0,0)(0,82)(199,82)(199,0)

类型1必须作为类块存储,具有以下属性:BlockID,BlockType,number_of_edges,lowerleft,rightright,upperleft,upperright。

类型2: SB1 softrectangular 24045 0.300 3.000

类型2也必须被存储作为一类块,具有以下属性:BLOCKID,BlockType,面积,min_aspectRatio,max_aspectRatio。

是否有可能建立所谓的“块”一个类,有一组不同的视属性“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;} 
+0

“class block”是什么意思?请提供一些代码,显示您想要实现的内容。 –

+0

听起来也许用例的模板。 –

+0

我的意思是一个叫做块的类。我编辑了这个问题。基本上,解析器来解析上述两种不同类型的线的成称为“块”的类。但取决于“BlockType”属性,它必须具有不同的属性。 –

回答

0

一个简单的方法来做到这一点是使用工会。工会一次只能有1个活跃成员,并且只占用与最大成员相同的大小。

#include <iostream> 
using namespace std; 

class Block { 
    public: 
    struct Type1 { 
     int number_of_edges; 
     float lowerleft, lowerright, upperleft, upperright; 
    }; 
    struct Type2 { 
     double area; 
     float min_aspectRatio, max_aspectRatio; 
    }; 

    union combinedData { 
     Type1 t1; 
     Type2 t2; 
    }; 

    int BlockID; 
    int BlockType; 

    combinedData data; 
}; 

int main() { 
    Block block; 
    block.BlockType = 1; 
    block.data.t1.number_of_edges = 1; // Type1 is now active 
    cout << block.data.t1.number_of_edges << endl; 
    block.BlockType = 2; 
    block.data.t2.area = 1.5678; // Switched to Type2 being the active member 
    cout << block.data.t2.area << endl; 
} 

然后,您可以使用BlockType的值来确定哪个成员处于活动状态。