函数指针在C、C++中的应用是有所区别的,如
int Add(int x1,int x2)
{
return x1+x2;
}
int main()
{
int (*p)(int,int);
p=Add;
int nRet = (*p)(1,2); //nRet = 3
}
在使用class的函数指针方面,应有所区别,如
class CTest
{
public:
int Add(int x1,int x2);
void Test();
};
int CTest::Add(int x1,int x2)
{
return x1+x2;
}
void CTest::Test()
{
int (CTest::*f)(int,int);
f = Add;
int nRet = (this->*f)(1,2); //为什么一定要注明this->呢? 是需要指明这个object对象吗?
}
void main()
{
CTest c;
int (CTest::*p)(int,int);
p=CTest::Add;
int nRet = (c.*p) (1,2);
}
在使用C++的函数指针时,为什么一定要注明类的域呢?我想是由于C、C++中函数的压栈方式不同,所以不能写成 int (*f)(int,int);而需要写为int (CTest::*f)(int,int); 这种方式
另外还有几点疑问的地方,希望能有高手讲解明白。。。 。。。