如何在衍生类中重新声明模式

How to redeclare a pattern in a derivative class?

本文关键字:新声明 声明 模式      更新时间:2023-10-16

我有一个基类:

class BaseClass {
private:
    typedef void ( BaseClass::*FunctionPtr ) ( std::string );
    FunctionPtr funcPtr;
public:
    void setFunc( FunctionPtr funcPtr ) {
        this->funcPtr = funcPtr;
    }   
}

现在我需要创建一个衍生类:

class DerivativeClass: public BaseClass {
public:
    // I can overload the FunctionPtr here but for what?
    // then I also need to overload setFunc() function but I can't do it 
    // because I have too much code in a BaseClass which works with funcPtr.
    // I mean works with some function from this DerivativeClass.
    typedef void ( DerivativeClass::*FunctionPtr ) ( std::string );
    // therefore it has not any common sense in using BaseClass at all if I
    // will overload all its functions here.
    void callMe() {
        printf( "Ok!n" );
    }
    void main() { // the program starts here
        setFunc( &DerivativeClass::callMe ); // here's my problem
    }
}

我在那里有一个问题,因为 setFunc() 仅从 BaseClass 获取指向函数的指针,但我需要设置指向 DerivativeClass::callMe 函数的指针。如何解决这个问题?也许有一些使用模板的好解决方案?

好吧,

我为这个问题找到了一些很酷的解决方案。看:

template < class T >
class BaseClass {
private:
    typedef void ( T::*FunctionPtr ) ();
    FunctionPtr funcPtr;
public:
    void setFunc( FunctionPtr funcPtr ) {
        this->funcPtr = funcPtr;
    }
};
class DerivativeClass: public BaseClass < DerivativeClass > {
public:
    void callMe() {
        printf( "Ok!n" );
    }
    void main() { // the program starts here
        setFunc( &DerivativeClass::callMe );
    }   
};

如果您对此有任何建议 - 我非常感谢:)