gpt4 book ai didi

c++ - 如何在派生类中重新声明模式?

转载 作者:太空宇宙 更新时间:2023-11-04 13:41:38 26 4
gpt4 key购买 nike

我有一个基类:

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 );
}
};

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

关于c++ - 如何在派生类中重新声明模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27471865/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com