我喜欢使用接口来隐藏我的实现细节。我也非常喜欢使用继承作为构建我以前创建的类的方法。如何让这两种好处共存?这是我的问题的一个例子:
object.h
class object {
protected:
//stuff that should be available to derived classes
virtual void derivedHelper () = 0;
public:
//stuff that should be available to the client
virtual object* create () = 0;
virtual void mainTask () = 0;
}
object.cpp
class objectPriv : public object {
private:
//implementation specific details and members
protected:
void derivedHelper () {
//some stuff
}
public:
objectPriv() { }
object* create () {
return(new objectPriv());
}
void mainTask () {
//more stuff
}
}
superObject.h
class superObject : public object { //problem #1
public:
//stuff that should be available to the client
virtual superObject* create () = 0;
}
superObject.cpp
class superObjectPriv : public superObject { //problem #2
private:
//the magic behind super object
public:
superObjectPriv() { }
superObject* create () {
return(new superObjectPriv());
}
void mainTask () {
object::mainTask(); //problem #3
object::derivedHelper(); //problem #4
//super extra stuff
}
}
所以你可以在这里看到这不会编译。
我可以为superObject实现对象的纯虚拟对象,但这会破坏从对象派生的目的。我不想复制实现,我想在它上面构建。
我可以将superObject更改为从objectPriv派生,但之后我将公开我的实现细节。我想隐藏所有关于objectPriv的具体内容。
我无法想到实现这一目标的任何方法。我有一种不好的感觉,这可能是不可能的,但是我的手指交叉,你们大家会有一些聪明的伎俩:)
由于 莱斯
答案 0 :(得分:0)
您是否考虑过mixin模式?这是一种向多个类添加共享实现的方法。一个定义了一个模板类,它源自它的参数。你可以使用ObjectPriv和SuperObjectPriv的常见行为来做到这一点:
template <typename ParentT>
class CommonFunctionalityMixin
: public ParentT // this is the magic line that makes it a mixin
{
public:
typedef ParentT parent_type;
virtual void mainTask() { /* implementation */ }
virtual void derivedHelper() { /* implementation */ }
};
class ObjectPriv
: public CommonFunctionalityMixin<object> // which derives from object
{
public:
typedef CommonFunctionalityMixin<object> parent_type;
virtual object* create() { return new ObjectPriv; }
// virtual void mainTask() defined in CommonFunctionalityMixin
// virtual void derivedHelper() defined in CommonFunctionalityMixin
};
class SuperObjectPriv
: public CommonFunctionalityMixin<superObject> // which derives from superObject
{
public:
typedef CommonFunctionalityMixin<object> parent_type;
virtual object* create() { return new SuperObjectPriv; }
// now we override CommonFunctionalityMixin's mainTask() with super's
virtual void mainTask()
{
parent_type::mainTask();
parent_type::derivedHelper();
}
};