填充子类的基类向量不起作用

Cub*_*ner -1 c++ polymorphism inheritance class stdvector

我正在尝试使用具有相同基类的不同子类指针的向量。该向量设置为基类指针,但是添加到该向量的任何内容都无法获得其子类的全部功能。在错误日志中可以看到,它被视为基类,因此未获得扩展功能。

我查看了很多问题,人们说要按照我的方式去做,但是由于某种原因,它没有用。

该代码位于公共仓库中:

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 being set as a base class and
                                          // not getting the functionality of the subclass it is.
}
Run Code Online (Sandbox Code Playgroud)

JeJ*_*eJo 5

通常,这是通过虚拟功能实现的。在给定的情况下,它应该是一个虚拟的getter函数,该函数返回char每个类的成员。

class Base {
    char A = 'A';
public:
    virtual char getChar()const /*noexcept*/ { return A; }
    virtual Base () = default;
};

class Sub : public Base {
    char B = 'B';
public:
    char getChar()const /*noexcept*/ override { return B; }
};

class Sub2 : public Base {
    char C = 'C';
public:
    char getChar()const /*noexcept*/ override { return C; }
};
Run Code Online (Sandbox Code Playgroud)

现在主要

std::cout << List[0]->getChar() << std::endl;
Run Code Online (Sandbox Code Playgroud)

作为附带说明,我建议您看一下智能指针而不是行指针,通过它可以避免手动进行内存管理。

一个好的开始将是:

#include <memory>

std::vector<std::unique_ptr<Base>> List;
List.emplace_back(std::make_unique<Sub>());
Run Code Online (Sandbox Code Playgroud)

  • 基类应该有一个虚拟的析构函数。还请确保在完成处理后删除向量中的对象,因为这不是向量析构函数执行的,否则会导致内存泄漏。 (2认同)