如何使用动态对象数组实现基类成员函数?

时间:2015-11-09 12:08:04

标签: c++ arrays dynamic polymorphism

我试图找出使用动态对象数组(使用指向基类的指针数组)实现基类成员函数的正确方法。我有一个动物基类,爬行动物和哺乳动物来自那里,然后是这两个衍生的多个类。我尝试通过gdb运行以下代码,特别是当我尝试通过交换机上的案例四时,它给了我一个分段错误。

class Zoo
{
    Animal ** _zoo;

public:
    Zoo();
    ~Zoo();
    void Run();
};
#endif

const unsigned MAX_ZOO = 20;

Zoo::Zoo()
{
    _zoo = new Animal*[MAX_ZOO];
}

Zoo::~Zoo(){}

void Zoo::Run()
{
    unsigned pick = 1;
    unsigned element = 0;
    unsigned choose;
    while (pick != 5)
    {
        pick = select_option();
        switch (pick)
        {
    case 1:
           cout << "Is the animal a mammal(1) or reptile(2)?" << endl;
           cin >> choose;
           if (choose == 1)
           {
            cout << "Is this animal an elephant(1), skunk(2), or other(3)?"      << endl;
            cin >> choose;
            if (choose == 1)
                _zoo[element] = new Elephant();
            else if (choose == 2)
                _zoo[element] = new Skunk();
            else
                _zoo[element] = new Mammal();
           }
           else if (choose == 2)
           {
            cout << "Is this animal a python(1), crocodilia(2), or other(3)?" << endl;
                cin >> choose;
                if (choose == 1)
                    _zoo[element] = new Python();
                else if (choose == 2)
                    _zoo[element] = new Crocodilia();
                else
                    _zoo[element] = new Reptile();
           }
       element += 1;
       break;
    case 2:
        for ( unsigned i = 0; i < element; i++)
            _zoo[element]->Feed();
        break;
    case 3:
        for ( unsigned i = 0; i < element; i++)
            _zoo[element]->CageMaintenance();
        break;
    case 4:
        for ( unsigned i = 0; i < element; i++)
            _zoo[element]->Display();
        break;
    }
}

这是实现基类函数的正确方法吗?

0 个答案:

没有答案