用不同的 class 填充一个数组,它们都继承自相同的 class
Fill an array with different classes which all inherit from the same class
我的情况是这样的:
class Parent;
class Child1 : public Parent;
class Child2 : public Parent;
class ChildOfChild1 : public Child1;
std::vector<std::vector<Parent>> matrix;
我希望能够在这个矩阵中包含所有 类,但我不确定最好的方法。
现在,如果我添加到矩阵中的每个子项都保留原样,则会转换为一个父项,并删除父项中未包含的所有方法和变量。
我知道这样的事情在 Java 中应该是可能的,它也是严格类型化的,所以我想我可能会问在 C++ 中是否也可能。
我认为它是 this question
的副本
你要用的东西叫做Object Slicing
试试这个:
std::vector<std::vector<Parent*>> matrix
我的情况是这样的:
class Parent;
class Child1 : public Parent;
class Child2 : public Parent;
class ChildOfChild1 : public Child1;
std::vector<std::vector<Parent>> matrix;
我希望能够在这个矩阵中包含所有 类,但我不确定最好的方法。
现在,如果我添加到矩阵中的每个子项都保留原样,则会转换为一个父项,并删除父项中未包含的所有方法和变量。
我知道这样的事情在 Java 中应该是可能的,它也是严格类型化的,所以我想我可能会问在 C++ 中是否也可能。
我认为它是 this question
的副本你要用的东西叫做Object Slicing 试试这个:
std::vector<std::vector<Parent*>> matrix