类里面经常会遇到函数指针与对象指针的问题,并且经常容易出错,所以整理一下,以备后用!!
#include <iostream>
using namespace std;
class father
{
public:
void foo()
{
cout<<"this is the foo"<<endl;
}
};
class son :public father
{
public:
void fool()
{
cout<<"this is the son fool"<<endl;
}
};
int main()
{
son *s=new father; //1 error
father *f=new son; //2 OK
void(son::*pFun1)()=&father::foo; //3 OK
void(father::*pFun2)()=&son::fool;// 4 error;
return 0;
}
但是如果我的指针是son类型的,但是你给的空间是father类型的,就是申请的空间不足,那就有问题了;
函数指针刚好相反,子类的函数指针可以指向父类,但是父类的函数指针不能指向子类!!