我有一个数据结构,我想在不同情况下以不同方式访问/修改它。我想到了这个:
class DataStructure
{
public:
int getType();
private:
// underlying data containers
};
class WrapperBase
{
public:
void wrap(DataStructure *input)
{dataStructure = input;}
protected:
DataStructure *dataStructure;
};
class WrapperOne : public WrapperBase
{
public:
// @Mykola: I know bytes 4-10 in an array of type one specify the date
// so this method will format those bytes and return them
Data getDate()
};
class WrapperTwo : public WrapperBase
{
public:
// @Mykola: There is mostly just a chunk of data in packet type two. So this
// method will turn 4 bytes into an int at position index and return that
int dataAt(int index);
};
我在这里看到的一个问题是 WrapperBase 不是抽象的,尽管它应该是。我当然可以在构造函数中添加一些纯虚拟虚拟函数 或 assert(0) 但这似乎是一个太过分的解决方案。或者我应该完全摆脱继承,因为它只是为了代码重用才真正完成的?此解决方案还有其他问题吗?
还是我完全走错了路?
编辑@Paul
我为什么要这样做?好吧,我得到了几个 1000 个序列化数据数组,我想将它们添加到数据集中。每个数组的前几个字节告诉我它是什么类型的数据,这决定了我如何处理它。那么我会做类似的事情:
// some place in the program
dataSet.processData(dataStructure);
// in the data set class
DataSet::processData(DataStructure *dataStructure)
{
if(dataStructure->getType() == TYPE_ONE)
{
WrapperOne wrapperOne;
wrapperOne.wrap(dataStructure);
processDataTypeOne(wrapperOne);
}
// repeat the above for other data types
}
我当然可以将所有逻辑放在 processDataTypeOne
函数中,这就是我一开始所做的,但对原始数据结构的操作变成了索引操作的丑陋困惑。这就是为什么我想将它包装在一个对象中,这将隐藏所有这些内容。
最佳答案
考虑一下您希望数据的基类做什么。如果您要保存数据或将其显示到屏幕上,您可能需要一个具有 ToString 和 ToXML 等函数的基类。
让代码进化。写出您需要的不同 DataStructure 类。然后找到共性并将其移动到基类中。
关于c++ - 包装数据结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/614718/