派生对象指针可以存储在基类指针数组中吗?

时间:2016-06-27 16:08:15

标签: c++ pointers inheritance

假设我有一个基类指针数组。 我可以在此数组中存储派生类对象指针(从该基类派生)吗?我可以反过来这样做吗?

2 个答案:

答案 0 :(得分:4)

  

我可以在这个数组中存储派生类对象指针(从该基类派生)吗?

  

我可以反过来做吗?

没有

说你有:

struct Base
{
};

struct Derived1 : Base
{
};

struct Derived2 : Base
{
};

std::vector<Derived1*> ptrs;
Base* bPtr = new Derived2;
ptrs.push_back(bPtr);        // Not allowed.
                             // If it were, imagine the problems.
                             // You have a Derived2* in the guise of a Derived1*

答案 1 :(得分:3)

您确实可以将Derived*存储在Base*数组(或Base指针的任何其他数据结构中。)

但反之亦然,因为它违反了Liskov Substitution Principle