基于基类传递给功能的对象数组

时间:2019-04-11 07:23:44

标签: c++ arrays

我想实现一个对多种类型的类对象数组进行操作的函数。 函数接收基于基类ptr的类数组。 类数组是引用,并传递给此函数以存储数组。

我不想使用模板或任何STL容器,例如地图,矢量或列表等。 我有下面的示例程序,但由于打印功能无法将对象转换为特定类型而出现分段错误。

这如何实现?

#include <string>

typedef enum {
    CLASS_TYPE_1 = 0,
    CLASS_TYPE_2,
    CLASS_TYPE_3, 
    CLASS_TYPE_4 
}ClassType;

class Base {

public:    
    virtual ClassType GetType() = 0;
    virtual void print() = 0;
};

class ClassType1 : public Base {

public: 
    int index;

    ClassType1(int index) {
        this->index = index;
        printf("ClassType1: index[%d] \n", index);
    }

    virtual ClassType GetType() { 
        return CLASS_TYPE_1;
    };

    virtual void print() {
        printf("print called index[%d] \n", index);    
    }
};


class ClassHolder {

    ClassType type;    
    Base *baseArray;
    int arraySize;

public:

    void setArray(Base *array) {
        this->baseArray = array;
    }

    void setType(ClassType type) {
        this->type = type;
    }

    void setArraySize(int size) {
        this->arraySize = size;
    }

    void print(int index) {
        if (index < arraySize) {
            if (type == CLASS_TYPE_1) {
                //((ClassType1&)baseArray[index]).print(); // <------ Segmentation fault (core dumped) 
            }
            else if(type == CLASS_TYPE_2) {
                //((ClassType2&)baseArray[index]).print(); // <------ Segmentation fault (core dumped) 
            }
        }
    }

};

int main()
{
    ClassHolder holder;
    ClassType1 array[] = {1, 2, 3, 4, 5};

    holder.setType(CLASS_TYPE_1);
    holder.setArray(array);
    holder.setArraySize(5);
    holder.print(1);

    return 0;
}

谁可以避免此错误?

1 个答案:

答案 0 :(得分:0)

 ((ClassType1&)baseArray[index]).draw();

必须替换为

((ClassType1 *)baseArray)[index].print();

cast (ClassType1&)baseArray[index]是错误的,因为您将 baseArray 用作Base*,不是,您必须指出 baseArray ClassType1 *,可以通过正确的方式访问它