Store derived object in vector of base type
我有一个基类类型指针的std::vector:
1 | vector<Base*> baseList; |
我把一个派生类类型推到向量上:
1 2 | Derived* derivedObject = new Derived(); baseList.push_back(derivedObject); |
但当我迭代列表并调用派生类从基类重写的函数时,不会调用派生类中的代码。我用向量的方法正确吗?
我的基类在声明其函数之前使用了虚关键字,派生类用以下方法派生基类:
1 | class Derived : public Base |
知道我在这里做错什么了吗?
编辑:
要调用我声明的函数:
1 2 3 | typedef vector<App*>::iterator AppIterator; AppIterator begin() { return l_Apps.begin(); } AppIterator end() { return l_Apps.end(); } |
我这样称呼这个函数:
1 2 3 4 | for (AppIterator it = begin(); it != end(); ++it) { (*it)->Initialize(); } |
问题会在这里吗?
我用迭代器试过了…这段代码对我来说很好,所以如果问题仍然存在,请考虑使用不同的编译器=)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | #include <iostream> #include <vector> class Base { public: virtual void f() { std::cout <<"Base "; } }; class Derived: public Base { public: virtual void f() { std::cout <<"Derived "; } }; int main() { std::vector<Base*> s; s.push_back(new Base()); s.push_back(new Derived()); s.push_back(new Base()); s.push_back(new Derived()); s.push_back(new Base()); s.push_back(new Derived()); for (std::vector<Base*>::iterator it = s.begin(); it != s.end(); ++it) { (*it)->f(); } return 0; } |
我的输出:
1 2 3 4 5 6 | Base Derived Base Derived Base Derived |
另外,您可能会尝试使用