您的位置:首页 > 其它

函数指针

2015-12-05 16:43 127 查看
1.函数指针

void square(int& refX, int& refY)
{
cout << "square..." << endl;
}
void cube(int& refX, int& refY)
{
cout << "cube..." << endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
void(*pFunc)(int&, int&);
int oneVal = 12, twoVal = 45;
pFunc = square;
pFunc(oneVal, twoVal);
pFunc = cube;
pFunc(oneVal, twoVal);
}
2.函数指针数组
void(*pFunc[2])(int&, int&);
int oneVal = 12, twoVal = 45;
pFunc[0] = square;
pFunc[1] = cube;

pFunc[0](oneVal, twoVal);
pFunc[1](oneVal, twoVal);3.将函数指针传递给其他函数
void square(int& refX, int& refY)
{
cout << "square..." << endl;
}
void cube(int& refX, int& refY)
{
cout << "cube..." << endl;
}
void printValues(void(*)(int&, int&), int x, int y);//声明
void printValues(void(*pFunc)(int&, int&), int x, int y)//实现
{
pFunc(x, y);
}

int _tmain(int argc, _TCHAR* argv[])
{
printValues(square, 12, 23);
printValues(cube, 1, 2);

}

4.用typedef简化函数指针的定义
typedef void(*pFunc)(int&, int&); //typedef定义
void square(int& refX, int& refY)
{
cout << "square..." << endl;
}
void cube(int& refX, int& refY)
{
cout << "cube..." << endl;
}
void printValues(pFunc func, int x, int y);//声明
void printValues(pFunc func, int x, int y)//实现
{
func(x, y);
}

int _tmain(int argc, _TCHAR* argv[])
{
printValues(square, 12, 23);
printValues(cube, 1, 2);
}5.指向类成员函数的函数指针
class Dog
{
public:
Dog(){};
~Dog(){};
void speak(int&, int&) const{ cout << "Dog speak!" << endl; }

private:

};

int _tmain(int argc, _TCHAR* argv[])
{
void(Dog::*pClassFunc)(int&, int&) const = 0; //定义
pClassFunc = &Dog::speak; //赋值

int oneVal = 12, twoVal = 9;
Dog dog;
(dog.*pClassFunc)(oneVal, twoVal);//调用
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: