指向基类的数组,填充派生类 [英] Pointer to array of base class, populate with derived class
问题描述
如果我有一个基类,只有虚拟方法,并从2派生类
基类,与实现这些虚拟的方法。
If I have a base class, with only virtual methods and 2 derived classes from the base class, with those virtual methods implemented.
我如何:
// causes C2259
BaseClass* base = new BaseClass[2];
BaseClass[0] = new FirstDerivedClass;
BaseClass[1] = new SecondDerivedClass;
或
// causes "base is being used without being initialized"
BaseClass* base;
// causes CC59 again
BaseClass* base = new BaseClass;
base[0] = FirstDerivedClass();
base[1] = SecondDerivedClass();
(或类似的东西)
(or something similar)
......这样我就可以通过 DerivedClass
访问的BaseClass
取值方法,
但指针和指针 DerivedClass
S'
...so that I can access the BaseClass
s methods through the DerivedClass
,
but by pointer and the pointer is an array of DerivedClass
s?
推荐答案
您数组类型错误的:它存储的BaseClass
对象的实例的代替的指针的给他们。由于的BaseClass
似乎是抽象的,编译器会抱怨它不能缺省方式构造的实例来填补你的阵列。
Your array is of the wrong type: it stores BaseClass
object instances instead of pointers to them. Since BaseClass
seems to be abstract, the compiler complains that it cannot default-construct instances to fill your array.
即使的BaseClass
是不是抽象的,使用数组多态是<一个href=\"https://www.securecoding.cert.org/confluence/display/cplusplus/ARR39-CPP.+Do+not+treat+arrays+polymorphically\">big没有没有在C ++中,所以你应该在任何情况下做不同的事情。
Even if BaseClass
were not abstract, using arrays polymorphically is a big no-no in C++ so you should do things differently in any case.
通过改变code来解决这个问题:
Fix this by changing the code to:
BaseClass** base = new BaseClass*[2];
BaseClass[0] = new FirstDerivedClass;
BaseClass[1] = new SecondDerivedClass;
这是说,大部分的时间是preferable使用的的std ::矢量
不是纯数组和智能指针(如的std :: shared_ptr的
),而不是愚蠢的指针。使用这些工具,而不是手工编写code的会照顾问题的主机透明地在一个非常小的运行成本。
That said, most of the time it is preferable to use std::vector
instead of plain arrays and smart pointers (such as std::shared_ptr
) instead of dumb pointers. Using these tools instead of manually writing code will take care of a host of issues transparently at an extremely small runtime cost.
这篇关于指向基类的数组,填充派生类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!