2013-04-21 97 views
2

假设我有一个抽象基类称为Base和它继承调用Rectangle其他类(W/C具有X,Y,W,H的属性)C++继承功能默认操作

//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 

}; 

对于所有继承此Base的类,它必须实现这个短期操作第一:

void OtherClass1::PerformTask() 
{ 

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

    //else, proceed with the overriden operation 

    //... 
} 
PerformTask()

,可以把它做一个默认操作,因为我不会在所有执行重新键入它,但是,在同一时间,被覆盖并且short operation被首先执行并保留?

+2

然后不要让'Base :: PerformTask'纯虚拟。 – 0x499602D2 2013-04-21 16:25:22

回答

4

是的,这是可以做到的;只是让PerformTask它调用实际重写功能的非虚拟函数:

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

    PerformTaskImpl(); 
} 

virtual void PerformTaskImpl() = 0; 

...然后只是覆盖在派生类PerformTaskImpl

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

+0

我如何知道在其他人之前是否先执行了“短操作”? – mr5 2013-04-21 16:28:31

+0

@ mr5对不起,我不明白这个问题。 – 2013-04-21 16:29:36

+0

我的意思是,唯一不会被覆盖的就是“短操作”,并将为每个继承它的类保留。 – mr5 2013-04-21 16:35:07