[英]How to call a function by a pointer?
我有一些基類,我在其中存儲指向派生類中的函數的指針。 我需要從兩個位置通過其指針調用函數:從BaseClass和從派生類。
template < class T >
class BaseClass {
private:
typedef void ( T::*FunctionPtr ) ();
FunctionPtr funcPtr;
public:
void setFunc( FunctionPtr funcPtr ) {
this->funcPtr = funcPtr;
( this->*funcPtr )(); // I need to call it here also but it doesn't work
}
};
class DerivedClass: public BaseClass < DerivedClass > {
public:
void callMe() {
printf( "Ok!\n" );
}
void mainFunc() {
setFunc( &DerivedClass::callMe );
( this->*funcPtr )(); // works fine here
}
};
錯誤:指向-> *的左操作數必須是指向與右操作數兼容的類的指針,但它是'BaseClass *'
( this->*funcPtr )();
是錯誤的語法使用調用funcPtr
因為類型funcPtr
是void T::*()
您需要使用:
( (static_cast<T*>(this))->*funcPtr )();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.