基于更有效的 C++条款 3:永远不要多态处理数组,我们应该避免多态处理数组。
那么为什么我们可以std::vector
毫无问题地使用来保存指向基类的指针呢?
谢谢
#include <iostream>
#include "boost/shared_ptr.hpp"
#include <vector>
class BaseClass {
public:
virtual void PrintMe() const {
std::cout << "BaseClass" << std::endl;
}
virtual ~BaseClass() {}
};
class SubClass : public BaseClass {
public:
virtual void PrintMe() const {
std::cout << "SubClass" << std::endl;
}
};
int main()
{
std::vector<boost::shared_ptr<BaseClass> > vecPtrs;
boost::shared_ptr<BaseClass> shp1(new BaseClass);
vecPtrs.push_back(shp1);
boost::shared_ptr<BaseClass> shp2(new SubClass);
vecPtrs.push_back(shp2);
for (size_t i = 0; i < vecPtrs.size(); ++i)
{
vecPtrs[i]->PrintMe();
}
}
// Output:
BaseClass
SubClass
Press any key to continue . . .