ana*_*lyg 9 c c++ function-pointers
阅读C++标准,我看到有"函数"类型和"函数指针"类型:
typedef int func(int); // function
typedef int (*pfunc)(int); // pointer to function
typedef func* pfunc; // same as above
Run Code Online (Sandbox Code Playgroud)
我从未见过在示例之外使用的函数类型(或者我可能没有认识到它们的用法?).一些例子:
func increase, decrease; // declares two functions
int increase(int), decrease(int); // same as above
int increase(int x) {return x + 1;} // cannot use the typedef when defining functions
int decrease(int x) {return x - 1;} // cannot use the typedef when defining functions
struct mystruct
{
func add, subtract, multiply; // declares three member functions
int member;
};
int mystruct::add(int x) {return x + member;} // cannot use the typedef
int mystruct::subtract(int x) {return x - member;}
int main()
{
func k; // the syntax is correct but the variable k is useless!
mystruct myobject;
myobject.member = 4;
cout << increase(5) << ' ' << decrease(5) << '\n'; // outputs 6 and 4
cout << myobject.add(5) << ' ' << myobject.subtract(5) << '\n'; // 9 and 1
}
Run Code Online (Sandbox Code Playgroud)
看到函数类型支持C中没有出现的语法(声明成员函数),我猜它们不仅仅是C++必须支持向后兼容性的C包的一部分.
除了展示一些时髦的语法之外,功能类型是否有用?
boost是一个有用的例子,你可以在其中经常看到它。例如在 signal2 库中:
boost::signals2::signal<void (int, int)> MySignal;
Run Code Online (Sandbox Code Playgroud)
其中上面声明了一个信号,该信号将接受任何采用两个 int 并具有 void 返回类型的函数。