【发布时间】:2015-07-17 12:44:08
【问题描述】:
我目前正在做一个小型游戏引擎,刚刚遇到了一个我没想到的问题。
我有一个根类,我的引擎中的大多数类都派生自 CPObject。 CPObject 符合 CPObjectProtocol,一个定义了一些纯虚函数的抽象类。
我创建了另一个协议TextureProtocol,它的具体实现SDLTexture也继承自CPObject。到目前为止,一切正常,我可以创建 SDLTexture 的实例。但是,如果我让 TextureProtocol 继承自 CPObjectProtocol,clang 会告诉我无法创建抽象类的实例。
我假设一个类可以通过继承另一个类的实现来实现接口。我错了吗?
// CPObject abstract interface/protocol
class CPObjectProtocol {
public:
virtual void retain() = 0;
virtual void release() = 0;
//more methods like this
};
// CPObject implementation.
class CPObject : public CPObjectProtocol {
public:
CPObject() { _retainCount = 0; }
virtual ~CPObject() { }
// implementation of CPObjectProtocol
virtual void retain() { _retain++; }
virtual void release() {
if(--_retainCount <= 0) {delete this;}
}
private:
int _retainCount;
};
// Texture absract interface/protocol
// inherits from CPObjectProtocol so that retain() and release()
// can be called on pointers to TextureProtocol (allowing for
// implementations to be swapped later)
class TextureProtocol : public CPObjectProtocol {
public:
virtual Color getColor() = 0;
};
// An implementation of TextureProtocol
// I assumed it would fulfil CPObjectProtocol by inheriting
// from CPObject's implementation?
class SDLTexture : public CPObject, public TextureProtocol {
public:
SDLTexture() { _id = 0; }
virtual ~SDLTexture { }
// implementation of TextureProtocol
virtual int getID() { return _id; }
private:
int _id;
}
【问题讨论】:
-
请贴一些真实的代码。我得到了几十个语法错误,如果我全部修复它们,代码就会编译。无论如何,您还需要在
CPObjectProtocol中使用虚拟析构函数。
标签: c++ inheritance abstract multiple-inheritance