环境:Windows x64,VS2015
用途:函数指针之前没有用到过,直到遇到一种情况:
开发某个功能,开头和结尾一样,中间过程复杂多样,但中间过程的输入和输出是一样的,
这种情况下,用函数指针代替中间过程的函数就比较方便
代码:普通函数、类成员函数、类静态函数 函数指针的使用
#include <iostream>
#include <string>
using namespace std;
class Person;
typedef int(*FuncTypeOne)(int); //普通函数
typedef int (Person::*FuncTypeTwo)(); //类成员函数
typedef int(*FuncTypeThree)(); //类静态函数,和普通函数相同,只是初始化的时候要加类名
int GetNumber(int input) //普通函数
{
return input;
}
class Person
{
public:
Person():m_name("ABC"),m_age(20) {};
~Person() {};
int GetAge() //类成员函数
{
return m_age;
}
int GetAgeTest(FuncTypeTwo fun)
{
return (this->*fun)();
}
static int GetCount() //类静态函数
{
return 100;
}
int GetCountTest(FuncTypeThree fun)
{
return fun();
}
private:
std::string m_name;
int m_age;
};
int main()
{
FuncTypeOne simpleFunc = &GetNumber;
int number = simpleFunc(50);
Person p;
int age = p.GetAgeTest(&Person::GetAge);
int count = p.GetCountTest(&Person::GetCount);
return 0;
}