我正在尝试使用具有相同基类的不同子类指针的向量。该向量设置为基类指针,但是添加到该向量的任何内容都无法获得其子类的全部功能。在错误日志中可以看到,它被视为基类,因此未获得扩展功能。
我查看了很多问题,人们说要按照我的方式去做,但是由于某种原因,它没有用。
该代码位于公共仓库中:
https://repl.it/@cubingminer8/inheritance-with-vectors-testing
任何帮助将不胜感激!
编辑:确定,所以我将在c ++ sdl2游戏引擎中将其用于子画面组系统。将有一个基本的Sprite类,其中包含一些基本的东西,例如render和move,而我需要的任何sprite都是它们自己的继承自Sprite的类,它们将具有自己的独特行为,因此虚函数是不切实际的。将有一个sprite组对象,可以将继承自Sprite的对象存储在其中。这样就可以一次全部渲染它们。
如果您曾经使用过pygame,那么它几乎与那里使用的sprite和spritegroup系统相同。 https://www.pygame.org/docs/tut/SpriteIntro.html
#include <iostream>
#include <vector>
class Base {
public:
char A = 'A';
};
class Sub : public Base {
public:
char B = 'B';
};
class Sub2 : public Base {
public:
char C = 'C';
};
int main() {
std::vector<Base*> List;
List.push_back(new Sub());
List.push_back(new Sub2());
std::cout << List[0]->B << std::endl; // it should be able to print B
std::cout << List[1]->C << std::endl; // but it is …Run Code Online (Sandbox Code Playgroud)