【问题标题】:How to Point a base class pointer array to a derived class object on a specific index如何将基类指针数组指向特定索引上的派生类对象
【发布时间】:2021-08-17 10:24:14
【问题描述】:
如何将索引 1 处的类 A 的指针数组指向派生类对象。所以当我写pointer[1].print()时,它会调用B类的打印函数。(它的索引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.
}
【问题讨论】:
标签:
c++
c++11
visual-c++
c++17
c++14
【解决方案1】:
A* pointer = new A[2]; 为两个As 保留空间。您只是不能将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 演示了初始化向量的其他方法,但这些也不一定更好。