为什么衍生类对象的指针数组无法声明

时间:2015-02-22 05:16:25

标签: c++ arrays pointers inheritance

可能重复:

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

这里我得到以下错误来定义这种类型的结构。实际上我想访问我在下面定义的KeyValue2类的一些额外方法。但我只能访问IKeyValue类方法,因为我无法在KeyValue2类中生成vectorKeyValue个对象指针。

请在代码评论中查看更多详情

错误:无法将"KeyValue2 **"类型的值分配给"IKeyValue **"类型的实体

代码:

class IKeyValue
{
    IKeyValue() {}
    virtual ~IKeyValue() {}
    virtual void setKey(int key) = 0;
    virtual void setValue(std::string value) = 0;
    virtual int getKey() = 0;
    virtual std::string getValue() = 0;
};

struct IVectorKeyValue
{
    // some methods with Virtual keyword and virtual destructor.
    IVectorKeyValue() {}
    virtual ~IVectorKeyValue() {}
    virtual void push_back(IKeyValue * item) = 0;
    virtual void pop_back() = 0;
    virtual IKeyValue * get(int index) = 0;
    virtual void set(int index, IKeyValue * item) = 0;
    virtual size_t size() = 0;
};

class KeyValue : public IKeyValue
{
public:
    // declare all methods of IKeyValue Base Class
    // This method is Extra Method, which i will use through derive class object
    std::string getValueIndex(int index);
    IVectorString* getVectorStringValues();
private:
    int key_;
};

class VectorKeyValue : public IVectorKeyValue
{

public:
    VectorKeyValue() : size_(0), capacity_(10)
    {
        vectorKeyValue_ = new KeyValue2 *[capacity_];
    }
    ~VectorKeyValue()
    {
        delete[] vectorKeyValue_;
        vectorKeyValue_ = NULL;
    }
   // declare all methods of IVectorKeyValue Base Class
private:
    size_t size_;
    size_t capacity_;
    IKeyValue **vectorKeyValue_;
};

int main()
{
    IVectorKeyValue *rootNode = new VectorKeyValue();
    // here I want to use some methods of KeyValue2 class, like getValueIndex and getVectorStringValues
    // But i cant use them. I do not know why.

    // getVectorStringValues method i am not able to access. because 
    // here rootNode->get(0) type is IkeyValue not KeyValue.
    rootNode->get(0)->getVectorStringValues();
    return 0;
}

任何帮助都将不胜感激。

谢谢&此致

1 个答案:

答案 0 :(得分:0)

实际上,指向子类型指针的指针不能隐式转换为指向超类型指针的指针。要了解原因,请考虑以下事项:

SuperType super;
SubType * sub_ptr = NULL;
SuperType * * super_ptr_ptr = &sub_ptr;    // illegal
*super_ptr_ptr = &super;

如果没有此限制,您可以将sub_ptr更改为指向super,而不会出现任何明确的强制转换或其他迹象表明存在类型系统违规。

(这与T * *无法隐式转换为const T * *的原因相同,即使T *可隐式转换为const T *。)