4

我可以更改此代码以使其正常工作吗?是否可以结合模板方法模式和多重继承?在不同的类中实现不同的算法似乎很方便。谢谢你。

class TBase {
public:
    virtual void Do1() const = 0;
    virtual void Do2() const = 0;

    void Do() const {
        Do1();
        Do2();
    }
};

class TFirstAlgorithm {
public:
    void Do1() const {}
};

class TSecondAlgorithm {
public:
    void Do2() const {}
};

class TAlgorithm
    : public TBase
    , public TFirstAlgorithm
    , public TSecondAlgorithm
{};
4

2 回答 2

3

从根本上说,您的问题是TFirstAlgorith::Do1TBase::Do1(同样TSecondAlgorithm::Do2TBase::Do2.

解决此问题的一种可能方法是使它们相关:

class TBase {
public:
    virtual void Do1() const = 0;
    virtual void Do2() const = 0;

    void Do() const {
        Do1();
        Do2();
    }
};

class TFirstAlgorithm : public virtual TBase {
public:
    void Do1() const { }
};

class TSecondAlgorithm : public virtual TBase {
public:
    void Do2() const { }
};

class TAlgorithm
    : public TFirstAlgorithm
    , public TSecondAlgorithm
{};
于 2012-06-08T21:26:50.453 回答
0

您可以使用 Do1 和 Do2 的实现并在其中调用适当的算法。

 class TBase {
    public:
        virtual void Do1() const = 0;
        virtual void Do2() const = 0;

    void Do() const {
        Do1();
        Do2();
    }
};

class TFirstAlgorithm {
public:
    void Do1() const {}
};

class TSecondAlgorithm {
public:
    void Do2() const {}
};

class TAlgorithm
    : public TBase
    , public TFirstAlgorithm
    , public TSecondAlgorithm
{
   virtual void Do1() const { TFirstAlgorithm::Do1() ; }
   virtual void Do2() const { TSecondAlgorithm::Do2() ; }  
};
于 2012-06-08T21:17:39.553 回答