所以我有一个班级Base
和一个班级Derived: public Base
。
baseInstance.doSomething()
将打印Base::doSomething()
。
derivedInstance.doSomething()
将打印Derived::doSomething()
。
以下是代码:
#include "Base.h"
#include "Derived.h"
#include <vector>
int main(){
Base base;
std::cout<<"Base should do something:\n";
base.doSomething();
Derived derived;
std::cout<<"\nDerived should do something:\n";
derived.doSomething();
std::vector<Base> vec;
vec.push_back(derived);
std::cout<<"\nDerived should do something:\n";
vec[0].doSomething();
return 0;
}
预期产出:
Base should do something:
Base::doSomething()
Derived should do something:
Derived::doSomething()
Derived should do something:
Derived::doSomething()
实际输出:
Base should do something:
Base::doSomething()
Derived should do something:
Derived::doSomething()
Derived should do something:
Base::doSomething()
如何在std::vector
中保留班级类型?
编辑: 但是对象切片不会单独留下方法实现吗?并删除多余的字段? 有没有办法环游这个?