简体   繁体   English

在C ++中扩展继承的数组

[英]Extending inherited array in C++

I have pointer, assume it should be array of class A. this pointer is defined in Ancesor class, as [2]. 我有一个指针,假设它应该是A类的数组。此指针在Ancesor类中定义为[2]。 it's set in constructor. 它在构造函数中设置。 the inheritor want to add 2 additional cells to this array, ie the array shall be [4]. 继承者要向该数组添加2个额外的单元格,即该数组应为[4]。

the constructor isn't offer the option to use overrided virtual methods. 构造函数不提供使用替代虚拟方法的选项。 so, how can I extends the array in inheritor to be 4 instead of 2, without creating the 2 in the ancesor, delete it in inheritor, and create new 4? 因此,如何在继承者中将数组扩展为4而不是2,而不在祖先中创建2,在继承者中将其删除,然后创建新的4?

BTW, it's not possible to use container such vector etc. it must be array. 顺便说一句,不可能使用容器,例如向量等,它必须是数组。

If you are setting the size of the array in the constructor, then the simplest solution is simply to overload the constructor. 如果要在构造函数中设置数组的大小,那么最简单的解决方案就是重载构造函数。

If you create a new constructor with a parameter being the size of the array, then you can simply call that ancestor constructor from within the derived class' constructor. 如果使用参数作为数组的大小创建新的构造函数,则只需在派生类的构造函数内调用该祖先构造函数。

In code: 在代码中:

Ancestor( unsigned int arraySize ){ array = new OBJECT[arraySize]; }

Then use that in the derived. 然后在派生中使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM