【发布时间】:2009-03-05 13:19:33
【问题描述】:
我有一个数据结构,我想在不同的情况下以不同的方式访问/修改。我想出了这个:
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) ,但这似乎是一个太老套的解决方案。或者我应该完全摆脱继承,因为它只是为了代码重用而完成的?此解决方案还有其他问题吗?
还是我完全走错了路?
编辑@保罗
我为什么要这样做?好吧,我得到了几个 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 函数中,这就是我一开始正在做的事情,但是对原始数据结构的操作变成了丑陋的索引操作混乱。这就是为什么我想将它包装在一个对象中,这将隐藏所有这些。
【问题讨论】:
-
请给我们至少一种方法 // 以其他方式访问/修改数据结构
标签: c++ inheritance data-structures oop