c - 为什么指针函数总是有 void 返回类型?

c - 为什么指针函数总是有 void 返回类型?

函数指针几乎可以有任何返回类型。考虑这个例子:

#include "stdafx.h"

#include

using namespace std;

// this defines a type called MathOp that is a function pointer returning

// an int, that takes 2 int arguments

typedef int (*MathOp)(int, int);

enum MathOpType

{

Add = 1,

Subtract = 2

};

// some generic math operation to add two numbers

int AddOperation(int a, int b)

{

return a+b;

}

// some generic math operation to subtract two numbers

int SubtractOperation(int a, int b)

{

return a-b;

}

// function to return a math operation function pointer based on some argument

MathOp GetAMathOp(MathOpType opType)

{

if (opType == MathOpType::Add)

return &AddOperation;

if (opType == MathOpType::Subtract)

return &SubtractOperation;

return NULL;

}

int _tmain(int argc, _TCHAR* argv[])

{

// declare a variable with the type MathOp, which is a function pointer to

// a function taking two int arguments, and returning an int.

MathOp op = &AddOperation;

std::cout << op(2, 3) << std::endl;

// switch the operation we want to perform by calling our one op variable

op = &SubtractOperation;

std::cout << op(2, 3) << std::endl;

// just an example of using a function that returns a function pointer

std::cout << GetAMathOp(MathOpType::Subtract)(5, 1) << std::endl;

std::getchar();

return 0;

}

上面的程序打印出 5、-1,然后是 4。函数指针可以有任何返回类型,并且非常强大。

相关推荐