【发布时间】:2015-02-22 05:16:24
【问题描述】:
可能重复:
Creating an array of pointers of derivative class objects. C++. Abstract base class
在这里,我在定义这种类型的类结构时遇到了错误。实际上我想访问我在下面定义的KeyValue2 类的一些额外方法。但我只能访问IKeyValue 类方法,因为在这里我无法在vectorKeyValue 类中创建KeyValue2 对象指针。
请在代码注释中查看更多详细信息
错误:"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;
}
任何帮助将不胜感激。
感谢和问候
【问题讨论】:
-
IKeyValue **和KeyValue2 **不兼容。您的阵列需要进行基本的设计修复。它只能包含IKeyValue *类型的指针,它可能指向KeyValue2对象。每个KeyValue2将被单独分配,而不是作为一个数组。 -
如果你使用
std::vector而不是重新发明轮子,它会让生活变得更轻松,如果你使用std::vector<std:;shared_ptr<IKeyValue *>>,可能会更容易。 -
@MattMcNabb 我不能使用矢量,这是关于我的作业的。请让我知道如何实现这一目标
-
将
new KeyValue2 *[capacity_];更改为new IKeyValue *[capacity_]();。并编写或禁用复制构造函数和复制赋值运算符。
标签: c++ arrays pointers inheritance