如何将基类指针数组指向特定索引上的派生类对象

问题描述

如何将索引 1 处的类 A 的指针数组指向派生类对象。所以当我写pointer[1].print()时,它从B类调用print函数。(它的索引0应该仍然指向A类型的对象)

#include <iostream>
using namespace std;
class A
{
protected:
string name;
public:
A()
{
name="A";
}
virtual void print()
{
cout<< name;
}
};


class B : public A
{

public:
B()
{
name="B";
}
void print()
{
cout<< name;
}
};

int main()
{
A *pointer=new A [2];
pointer[0].print(); //prints A

//Now I want index 1 to be pointed to object of child class B
//so when I write pointer[1].print()
// "B" is printed. 
}

解决方法

A* pointer = new A[2]; 为正好两个 A 保留空间。您只是不能B 强行插入此位置,因为(通常)它需要更多空间。

多态通常只能通过指针或引用起作用:

void demo1(A a);  // accept a by value; you *can* pass a B to,but then only its
                  // A part is copied,anything belonging to B gets lost
                  // this is called object slicing
void demo2(A& a); // now can accept both A and B without losing any
                  // type information
void demo3(A* a); // alike...

同样适用于数组,只是引用选项不可用:

A** array = new A*[2] { new A(); new B(); };

如果您通过 new 分配,请不要忘记 delete 以防止内存泄漏。

您可能希望使用智能指针来避免对创建的对象进行显式内存管理; std::vector 的智能指针使您完全无需进行任何内存管理(在上面的示例中,您还需要手动 delete[] array):

    std::vector<std::unique_ptr<A>> v;
    v.reserve(2);
    v.push_back(std::make_unique<A>());
    v.push_back(std::make_unique<B>());

不幸的是,std::initializer_list 构造函数不可用,因为 std::unique_ptr 不可复制。

演示了其他初始化向量的方法here,但这些也不一定更好。