【发布时间】:2011-07-13 19:43:43
【问题描述】:
好的,我不太清楚如何表达这个问题,也找不到任何我认为真正解决这种情况的重复项。
基本上我有一个超类,它通过子类获取额外的数据。此数据的容器类仅识别超类,并根据超类中的 id 参数调整特征。
实际上,直到最近我才不得不在 c++ 中使用继承,如果这是微不足道的,请原谅我。我的印象是,当我使用超类硬拷贝一堆数据时,可以说子类数据在翻译中丢失了。为了绕过这个限制,我尝试使用类型转换的指针,但是即使在 free() 函数中对指针参数进行类型转换,我现在在尝试释放内存时也会遇到分段错误。
这里是示例代码...
结构
// Super class
struct Vertex {
__declspec(align(4)) unsigned int vType; // Identifies the vertex type.
Vertex(const unsigned int _vType) : vType(_vType) { }
Vertex(const Vertex &_rV) : vType(_rV.vType) { } // Copy constructor
virtual ~Vertex() { }
unsigned int GetVType() const { return vType; }
};
// Subclass
// Id = 1
struct V_Pos : Vertex {
__declspec(align(4)) XMFLOAT3 position;
V_Pos(void) : Vertex(1) { }
V_Pos(XMFLOAT3 &_rPosition) : Vertex(1), position(_rPosition) { }
V_Pos(const V_Pos &_rV) : Vertex(_rV), position(_rV.GetPosition()) { } // Copy constructor
~V_Pos() { }
XMFLOAT3 GetPosition() const { return position; }
};
这是我目前复制数据的方式。
// pBuffer is declared as a Vertex* data type
pBuffer = new V_Pos[_bufSize];
if (_pVBuffer->GetVType() == 1)
for (unsigned int i = 0; i < bufSize; ++i) {
V_Pos *_temp = (V_Pos*)&_pVBuffer[i];
pBuffer[i] = *_temp;
}
这是我目前取消分配数据的方式。
if (pBuffer != 0) {
delete [] pBuffer;
pBuffer = 0;
}
这种情况的正确方法是什么?
编辑 1 -
更新了上述代码块,以澄清 knulp 回答下的评论讨论。
【问题讨论】:
-
为什么要使用子类来更新其超类?
-
@JAB - 我尝试用子类更新超类是为了获取附加的子类数据。整个顶点缓冲区被用作一个 BLOB,它被馈送到一个 COM 对象,然后被遗忘。
标签: c++ inheritance polymorphism