我有一个基类:
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函数的指针。我怎么解决这个问题?也许使用模板有一些很棒的解决方案?
答案 0 :(得分:0)
我已经找到了解决此问题的一些很酷的解决方案。看:
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 );
}
};
如果您对此有任何建议 - 我非常感谢:)