1. c++中允许用基类指针指向子类的对象,先亮出正确写法。
#include <iostream> #include <vector> using namespace std; class Base { public: virtual void print(); }; class Derived : public Base { public: virtual void print(); }; void Base::print() { std::cout << "\n IN Base" << std::endl; } void Derived :: print() { std::cout << "\n IN derived" << std::endl; } int main() { vector<Base*> baseclass; Base* ptrDerived = new Derived; baseclass.push_back(ptrDerived); Base* ptrBase = new Base; baseclass.push_back(ptrBase); baseclass.push_back(new Derived); vector<Base*>::const_iterator iter; for(iter = baseclass.begin(); iter != baseclass.end(); ++iter) { (*iter)->print(); } system("pause"); return 0; }
这种写法中print()是可以多态的虚函数,由不同的指针决定了访问基类的print();还是子类的print();