指向基类数组的指针,用派生类填充 [英] 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();
(或类似的东西)
...这样我就可以通过 DerivedClass
访问 BaseClass
的方法,但是通过指针,指针是 DerivedClass
的数组?
...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
对象 instances 而不是 pointers 给他们.由于 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
不是抽象的,多态使用数组也是一种 大禁忌,所以在任何情况下你都应该做不同的事情.
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.
通过将代码更改为:
BaseClass** base = new BaseClass*[2];
base[0] = new FirstDerivedClass;
base[1] = new SecondDerivedClass;
也就是说,大多数时候最好使用 std::vector
而不是普通数组和智能指针(例如 std::shared_ptr
)而不是愚蠢的指针.使用这些工具而不是手动编写代码将以极低的运行成本透明地处理大量问题.
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屋!