例1
#include "stdafx.h"
#include <iostream.h>
#include <string.h>
class student
{
protected:
int num;
char name[15];
public:
student(int no,char *pname):num(no)
{
strcpy(name,pname);
}
void print()
{
cout <<num << " " <<name<<endl;
}
};
void main()
{
student stu(12, "guyanhun ");
void (student::*p)(); //外部声明类中函数的函数指针类型,注意这里*号在右边括号
p=student::print; //外部给该函数指针赋值,赋类中的函数地址
(stu.*p)(); //外部调用该指针
}
例2
#include "stdafx.h"
class classTest{
public:
void( *classTest::pClassFun)(); //类中函数指针,注意这里*号在左边括号
static void print(){
printf("called print");
};
};
int main(int argc, char* argv[])
{
printf("Hello World!/n");
classTest ct;
ct.pClassFun=&ct.print; //外部将类中函数指针赋值为类中函数地址 ,注意这里print是static即静态函数,否则不能赋值
(*ct.pClassFun)(); //外部调用函数
return 0;
}
例3
#include "stdafx.h"
class classTest{
public:
void( *classTest::pClassFun)(); //类中函数指针,注意这里*号在左边括号
static void print(){
printf("called print");
};
void AssignFuncPointer(){pClassFun=print;};
};
int main(int argc, char* argv[])
{
//printf("Hello World!/n");
classTest ct;
ct.AssignFuncPointer(); //在类成员函数中给类中的函数指针赋值,注意这里print是static即静态函数,否则不能赋值
(*ct.pClassFun)(); //外部调用函数
return 0;
}
//若 print前面不加static
//error C2440: '=' : cannot convert from 'void (__thiscall classTest::*)(void)' to 'void (__cdecl *)(void)'