访问基类数组中的子类

Access child class in array of base class

本文关键字:子类 数组 基类 访问      更新时间:2024-05-10

我有一个基类数组,其中的项包含一个子类。问题是,当我尝试访问数组中的子类时,我在尝试访问时会得到错误no operator "[]" matches these operands

shared_ptr<P>& tmpP= (*arrayOfC)[(int)x][(int)y];

我正在尝试访问儿童类。如果我这样做:

arrayOfC[(int)x][(int)y]

然后我可以访问基类,而这不是我想要的。我尝试过使用dynamic_cast,但没有成功。

阵列是

shared_ptr<C> arrayOfC[800][600];

这是在另一个头文件中声明的,并且也使用正向声明。这就是它被保存的方式:

shared_ptr<P> childClassP= make_shared<P>(z, x, y);
arrayOfC[(int)x][(int)y] = std::move(childClassP);

您需要使用std::dynamic_pointer_cast,此外,您还需要在基类中至少有一个虚拟析构函数,以便生成vtables,使类具有多态性关联。

#include <memory>
struct C {
virtual ~C() {}
};
struct P : public C {
};
std::shared_ptr<C> arrayOfC[8][6];
int main() {
auto derived_ptr = std::make_shared<P>();
int x {2};
int y {2};
arrayOfC[x][y] = std::move(derived_ptr);
// does not compile: std::shared_ptr<P> view = arrayOfC[x][y];
std::shared_ptr<P> view = std::dynamic_pointer_cast<P>(arrayOfC[x][y]);
return 0;
}

请参阅http://www.cplusplus.com/reference/memory/dynamic_pointer_cast/

演示:https://godbolt.org/z/qn9oq4zfb