@BravoWA
2015-09-09T18:54:31.000000Z
字数 1057
阅读 3443
C++ OOP 多态 编程试验
在C++中,基类(父类)可能会派生出一个派生类(子类),然后派生类(子类)再作为基类派生出别的类(孙类)。那么在std::vector<父类*>时,到底孙类可不可放入这个vector中,C++ Primer没有说明。那进行一个编程实验进行验证。
IDE为VS2012,定义了三个类,base,child, grandson。child继承自base,grandson继承自child。
#include "stdafx.h"#include <iostream>#include <vector>using namespace std;class base {public:virtual void display() { cout << "This is base class!" << endl;}};class child : public base{public:virtual void display() { cout << "This is child class!" << endl;}};class grandson : public child {public:virtual void display() { cout << "This is grandson class!" << endl;}};int _tmain(int argc, _TCHAR* argv[]){vector<base*> basevec;vector<child*> childvec;base *Dad = new base;child *Son = new child;grandson *GrandSon = new grandson;basevec.push_back(GrandSon);basevec.push_back(Son);basevec.push_back(Dad);for (int i = 0; i < basevec.size(); i++){basevec[i]->display();}childvec.push_back(GrandSon);childvec[0]->display();cin.get();return 0;}
Screen Output:
This is grandson class!This is child class!This is base class!This is grandson class!
多层继承中,无论是第几层派生类均可将其指针push_back到其最顶端基类的vector<Base*>中。