首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

请问关于接口和继承的有关问题

2012-07-25 
请教关于接口和继承的问题?我想实现一个接口 ICollection,此接口只定义一些通用的方法。C/C++ code// 最底

请教关于接口和继承的问题?
我想实现一个接口 ICollection,此接口只定义一些通用的方法。

C/C++ code
// 最底层基类class DIRECT_UI IObject{public:    IObject();    virtual ~IObject();};/************* ICollection.h *************/// 定义接口class DIRECT_UI ICollection : public IObject{public:    ICollection();    virtual ~ICollection();public:    virtual int Add(IObject *pObject) = 0;    virtual void Insert(int index, IObject *pObject) = 0;    virtual void Remove(IObject *pObject) = 0;    virtual void RemoveAt(int index) = 0;    virtual void RemoveRange(int index, int count) = 0;    virtual int IndexOf(IObject *pObject) = 0;    virtual IObject* operator[](int index) = 0;    virtual int Count() = 0;    virtual void Clear() = 0;    virtual void SetParent(IObject *pObject) = 0;    virtual IObject* GetParent() = 0;};/************* UIElementCollection.h *************/// 接口的一个实现类 [IUIElement 派生于 IObject]class UIElementCollection : public ICollection{public:    UIElementCollection();    ~UIElementCollection();public:   virtual int Add(IUIElement *pUIElement);   virtual void Insert(int index, IUIElement *pUIElement);   virtual void Remove(IUIElement *pUIElement);   virtual void RemoveAt(int index);   virtual void RemoveRange(int index, int count);   virtual int IndexOf(IUIElement *pUIElement);   virtual IUIElement* operator[](int index);   virtual int Count();   virtual void Clear();  virtual void SetParent(IUIElement *pParent);  virtual IUIElement* GetParent();};编译错误:1>uielementcollection.h(42): error C2555: “UIElementCollection::operator []”: 重写虚函数返回类型有差异,且不是来自“ICollection::operator []”的协变1>icollection.h(30) : 参见“ICollection::operator []”的声明1>uielementcollection.h(42): error C2555: “UIElementCollection::GetParent”: 重写虚函数返回类型有差异,且不是来自“ICollection::GetParent”的协变1>icollection.h(36) : 参见“ICollection::GetParent”的声明


首先:请问,该如何解决上面的编译错误?
其次:我想知道我接口中定义的形如 Add(IObject *pObject) = 0; 这样的函数,其入参为 IObject* 类型,而我在 UIElementCollection 中定义为 Add(IUIElement *pUIElement); 是对原函数的一种重写,还是说重新定义了一个函数(即:此时既有Add(IObject *pObject),又有 Add(IUIElement *pUIElement); 函数 )。如果是第二种的话,请问该如何实现我预期的效果。
再次:如果我的 UIElementCollection 类并没有实现 ICollection 类中的全部函数,编译也是正常通过的。我记得好像是必须实现吧,为什么编译也会通过呢。

谢谢!!

[解决办法]
1. 你要把函数返回值改得和接口声明中的一样
2. 你这是重新定义了一个函数。把UIElementCollection中的改得和ICollection中的一样
3. 你没有实例化,所以可以编译通过。即你的代码中没 UIElementCollection e;或是UIElementCollection* p = new UIElementCollection();这样的語句

热点排行
Bad Request.