Creating an array of pointers of derivative class objects. C++. Abstract base class

给你一囗甜甜゛ 提交于 2019-12-11 10:50:03

问题


I need to make an array of 100 pointers to objects of two classes that are derived from an abstract class.

First element of array is of class B, second is C, third is B etc.

A is base and abstract class at the same time.

For example:

class A
{
 public:
   A();
   virtual double pureVirtualMethod() = 0;
};

class B: public A
{
};
class C: public A
{
};

In main() I need to make an array of pointers that will point to any of the derived classes.

I can't use Stl or Boost.


回答1:


The comments are right. You can google the answer in 5 seconds. In any case...

You need to define the body of the constructor for A, or remove the declaration and use the default one

Up to you to delete the array to avoid a memory leak :)

class A
{
 public:
   A() {} // <----- ADDED BODY
   virtual double pureVirtualMethod() = 0;
};

int main()
{
    A* names[100];
    for (int i = 0; i < 100; ++i)
    if (i % 2)
        names[i] = new C();
    else
        names[i] = new B();
}



回答2:


Since there isn't a question: make sure your base class has a virtual destructor. Without a virtual destructor you won't be able to easily delete the objects. To maintain the objects I would create a simple version of std::unique_ptr if I have to write it myself (well, for my own standard library implementation I, obviously, have an implementation anyway which I'd think I should be able to use...).



来源:https://stackoverflow.com/questions/18472479/creating-an-array-of-pointers-of-derivative-class-objects-c-abstract-base-cl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!