3 回答
TA贡献1906条经验 获得超3个赞
// 1 define a function pointer and initialize to NULLint (TMyClass::*pt2ConstMember)(float, char, char) const = NULL; // C++class TMyClass{public: int DoIt(float a, char b, char c){ cout << "TMyClass::DoIt"<< endl; return a+b+c;}; int DoMore(float a, char b, char c) const { cout << "TMyClass::DoMore" << endl; return a-b+c; }; /* more of TMyClass */};pt2ConstMember = &TMyClass::DoIt; // note: <pt2Member> may also legally point to &DoMore // Calling Function using Function Pointer(*this.*pt2ConstMember)(12, 'a', 'b');
TA贡献1875条经验 获得超3个赞
如何获得类成员函数的函数指针,然后使用特定对象调用该成员函数?
typedef
typedef void(Dog::*BarkFunction)(void);
->*
(pDog->*pBark)();
此外,如果可能的话,我也希望通过指针调用构造函数。这是可能的吗?如果可能的话,最好的方法是什么?
#include <iostream>class Animal{public: typedef Animal*(*NewAnimalFunction)(void); virtual void makeNoise() { std::cout << "M00f!" << std::endl; }};class Dog : public Animal{public: typedef void(Dog::*BarkFunction)(void); typedef Dog*(*NewDogFunction)(void); Dog () {} static Dog* newDog() { return new Dog; } virtual void makeNoise () { std::cout << "Woof!" << std::endl; }};int main(int argc, char* argv[]){ // Call member function via method pointer Dog* pDog = new Dog (); Dog::BarkFunction pBark = &Dog::makeNoise; (pDog->*pBark)(); // Construct instance via factory method Dog::NewDogFunction pNew = &Dog::newDog; Animal* pAnimal = (*pNew)(); pAnimal->makeNoise(); return 0;}
Dog*
Animal*
Dog* (*)()
Animal* (*)()
.
newDog
typedef
TA贡献1802条经验 获得超5个赞
this
boost::function
this
class myclass{ public: virtual void myrealmethod () = 0; static void myfunction (myclass *p);}void myclass::myfunction (myclass *p){ p->myrealmethod ();}
myfunction
编辑::
&myclass::myfunction
myclass::myfunction (arg);
.
- 3 回答
- 0 关注
- 516 浏览
添加回答
举报