-2

我正在为一个项目开发数据解析器。我必须解析一个可能包含两种不同类型对象的文件:

类型 1:sb0 hardrectilinear 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 时,我已经展示了解析器的实现。关于如何使用单个课程来做到这一点的任何想法?

软块.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;}
4

1 回答 1

0

一个简单的方法是使用联合。union 一次只能有 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 的值来确定哪个成员处于活动状态。

于 2017-10-21T22:26:07.177 回答