【问题标题】:Implementing a single class with different set of arguments使用不同的参数集实现单个类
【发布时间】: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”?还是什么?)然后您创建并填充适当的子类。您需要一组指向基类的指针。

标签: c++ class parsing sstream


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-02
    • 1970-01-01
    • 1970-01-01
    • 2017-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多