如何在衍生类中重新声明模式
How to redeclare a pattern in a derivative class?
我有一个基类:
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++ 声明类的静态成员?
- 垫子声明:声明尺寸和大小()不同
- 如何从构造函数声明新的私有变量?
- 使用具有新信号槽语法的Qt插件系统在接口类中声明信号
- 使用 basic_string 声明新类型的字符串
- 声明数组时出现 SIGSEGV 错误,而不创建新的 int[size]
- STD :: bad_alloc在声明新的int [n]时
- 了解函数错误的歧义新声明
- 在C++中,如何在没有新元素且不单独声明单个元素的情况下创建"std::initializer_list<base *>"?
- 使用模板在类中声明新函数
- 元编程:动态声明一个新结构
- 使用括号会在声明新节点时会产生错误
- QT应用程序声明新对象后崩溃
- 新声明在使用delete时包含垃圾值和堆损坏
- 为什么新运算符没有声明为 [[nodiscard]]?
- 您只是调用前方声明和原型声明“声明”
- C++:友元声明'声明一个非模板函数
- C++在新函数声明器语法中访问此