0

我喜欢使用接口来隐藏我的实现细节的想法。我也非常喜欢使用继承来构建我之前创建的类。我怎样才能让这两种好处共存?这是我的问题的一个例子:

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 的所有具体信息。

我想不出任何方法来实现这一点。我有一种不好的感觉,这可能是不可能的,但我祈祷你们会有一些聪明的把戏给我:)

谢谢莱斯

4

1 回答 1

0

你考虑过混合模式吗?这是一种将共享实现添加到多个类的方法。一个定义了一个从它的参数派生的模板类。您可以使用 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();
        }
};
于 2013-09-07T22:26:40.697 回答