我从以下代码开始:
#include <iostream>
class Base
{
private:
char a[4];
public:
Base(void){memcpy(a, "Base", 4);}
~Base(void){}
};
class Derived :
public Base
{
private:
char b[8];
public:
Derived(void){ memcpy(b, "Derived", 8);}
~Derived(void){}
};
要提取基类的数据,我将执行以下操作:
int main(void)
{
Derived derived;
char* onlyBase = new char[sizeof(Base) + 1];//+1 for '\0'
memcpy(onlyBase, &static_cast<Base>(derived), sizeof(Base));
onlyBase[sizeof(Base)] = '\0';
std::cout << onlyBase;
}
如何只获取课程派生部分的数据?
答案 0 :(得分:0)
hacky ,它可能适用于您的情况:
char* onlyDerived = new char[sizeof(Derived) - sizeof(Base) + 1];//+1 for '\0'
memcpy(onlyDerived, &reinterpret_cast<const char*>(&derived) + sizeof(Base), sizeof(Derived) - sizeof(Base));
onlyDerived[sizeof(Derived) - sizeof(Base)] = '\0';
我不鼓励你这样做,你可能有几个问题(不是便携式......,对齐,填充,字节序......)。
您可以执行以下操作:char* Base::serialize() const;
。