c++ - C++中的内存分配和继承类

标签 c++ inheritance dynamic-memory-allocation

假设我有这些结构:

struct Base{
 ...
}

struct Derived:public Base{
 //everything Base contains and some more
}

我有一个函数,我想在其中复制一个数组,然后更改它。

void doStuff(Base *data, unsigned int numItems){
 Base *newdata = new Base[numItems];
 memcpy(newdata, data, numItems*sizeof(Base));
 ...
 delete [] newdata;
}

但是如果我像这样使用这个函数:

Base *data = new Derived[100];
doStuff(data, 100);

这行不通,对吗?因为Derived1比Base大,所以给Base分配内存不够?

最佳答案

没错。这是 slicing problem 的变体.

关于c++ - C++中的内存分配和继承类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2292647/

相关文章:

c++ - 打印时 UINT16 值显示为 "backwards"

c++ - 为派生类生成唯一 ID

C++17:编译器支持 pmr 命名空间类

c - 使用指向结构的指针数组期间出现段错误

c++ - 从一个动态分配的数组复制到另一个 C++

C++ zilib deflate/inflate 和 ztream 参数

python - Python 中父类方法生成其子类实例的设计是否错误?

c# - 如何强制类实现派生自特定基类/接口(interface)(而不是特定类型)的属性

c - C中动态分配数组的数组

c++ - Klocwork 9 与 Klocwork 12