[关闭]
@BravoWA 2015-09-10T02:54:31.000000Z 字数 1057 阅读 3167

C++中派生类对象的指针放入基类的std::vector中(By BravoWA)

C++ OOP 多态 编程试验


1. 目的

在C++中,基类(父类)可能会派生出一个派生类(子类),然后派生类(子类)再作为基类派生出别的类(孙类)。那么在std::vector<父类*>时,到底孙类可不可放入这个vector中,C++ Primer没有说明。那进行一个编程实验进行验证。

2. 验证代码

IDE为VS2012,定义了三个类,base,child, grandson。child继承自base,grandson继承自child。

  1. #include "stdafx.h"
  2. #include <iostream>
  3. #include <vector>
  4. using namespace std;
  5. class base {
  6. public:
  7. virtual void display() { cout << "This is base class!" << endl;}
  8. };
  9. class child : public base{
  10. public:
  11. virtual void display() { cout << "This is child class!" << endl;}
  12. };
  13. class grandson : public child {
  14. public:
  15. virtual void display() { cout << "This is grandson class!" << endl;}
  16. };
  17. int _tmain(int argc, _TCHAR* argv[])
  18. {
  19. vector<base*> basevec;
  20. vector<child*> childvec;
  21. base *Dad = new base;
  22. child *Son = new child;
  23. grandson *GrandSon = new grandson;
  24. basevec.push_back(GrandSon);
  25. basevec.push_back(Son);
  26. basevec.push_back(Dad);
  27. for (int i = 0; i < basevec.size(); i++)
  28. {
  29. basevec[i]->display();
  30. }
  31. childvec.push_back(GrandSon);
  32. childvec[0]->display();
  33. cin.get();
  34. return 0;
  35. }

Screen Output:

  1. This is grandson class!
  2. This is child class!
  3. This is base class
  4. This is grandson class!

3. 结论

多层继承中,无论是第几层派生类均可将其指针push_back到其最顶端基类的vector<Base*>中。

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注