2

假设我有一个名为的抽象基类Base,它继承了另一个名为的类Rectangle(w/c 具有 x、y、w、h 的属性)

//Base.h

class Base abstract : public Rectangle
{
public:

    Base();

    void Show()
    {

        if (!visible) return;

        //draw the stuff here.

    }

    virtual void PerformTask() = 0;

protected:

    bool visible;
    bool enable;
    //other member variables

};

对于所有继承 this 的类Base,它必须首先实现这个简短的操作:

void OtherClass1::PerformTask()
{

    if (!enable) return; // <- this one I am referring to.

    //else, proceed with the overriden operation

    //...
}

PerformTask(),它是否可以进行默认操作,因为我不会在其所有实现中再次重新键入它,但同时会被覆盖并short operation首先执行并保留?

4

1 回答 1

4

是的,这是可以做到的;只需创建一个调用实际覆盖函数PerformTask的非虚拟函数:

// In Base:
void PerformTask() {
    if (not enabled) return;

    PerformTaskImpl();
}

virtual void PerformTaskImpl() = 0;

…然后PerformTaskImpl在派生类中重写。

这实际上是一种很常见的模式。

于 2013-04-21T16:25:47.963 回答