您的位置:首页 > 其它

How do I declare and use a pointer to a class member function?

2010-04-07 17:04 531 查看
How do I declare and use a pointer to a class member function? (top) The syntax is similar to a regular function pointer, but you also have to specify the class name. Use the .* and ->* operators to call the function pointed to by the pointer.
Collapse class CMyClass
{
public:
int AddOne ( unsigned n ) { return n+1; }
int AddTwo ( unsigned n ) { return n+2; }
};
main()
{
CMyClass myclass, *pMyclass = &myclass;
int (CMyClass::* pMethod1)(unsigned); // Full declaration syntax
pMethod1 = CMyClass::AddOne; // sets pMethod1 to the address of AddOne
cout << (myclass.*pMethod1)( 100 ); // calls myclass.AddOne(100);
cout << (pMyclass->*pMethod1)( 200 ); // calls pMyclass->AddOne(200);
pMethod1 = CMyClass::AddTwo; // sets pMethod1 to the address of AddTwo
cout << (myclass.*pMethod1)( 300 ); // calls myclass.AddTwo(300);
cout << (pMyclass->*pMethod1)( 400 ); // calls pMyclass->AddTwo(400); //Typedef a name for the function pointer type.
typedef int (CMyClass::* CMyClass_fn_ptr)(unsigned);
CMyClass_fn_ptr pMethod2;
// Use pMethod2 just like pMethod1 above....
} The line Collapse
int (CMyClass::* pMethod1)(unsigned);
pMethod1 is a pointer to a function in CMyClass; that function takes an unsigned parameter and returns an int. Note that CMyClass::AddOne is very different from CMyClass::AddOne(). The first is the address of the AddOne method in CMyClass, while the second actually calls the method.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: