进行C++编写程序时,你经常需要在一个函数中调用其他函数,此时就会考虑到使用函数指针,一个函数可以调用其他函数。在设计良好的程序中,每个函数都有特定的目的,普通函数指针的使用。
首先让我们来看下面的一个例子:
- #include <string>
- #include <vector>
- #include <iostream>
- using namespace std;
- bool IsRed( string color ) {
- return ( color == "red" );
- }
- bool IsGreen( string color ) {
- return ( color == "green" );
- }
- bool IsBlue( string color ) {
- return ( color == "blue" );
- }
- void DoSomethingAboutRed() {
- cout << "The complementary color of red is cyan!\n";
- }
- void DoSomethingAboutGreen() {
- cout << "The complementary color of green is magenta!\n";
- }
- void DoSomethingAboutBlue() {
- cout << "The complementary color of blue is yellow!\n";
- }
- void DoSomethingA( string color ) {
- for ( int i = 0; i < 5; ++i )
- {
- if ( IsRed( color ) ) {
- DoSomethingAboutRed();
- }
- else if ( IsGreen( color ) ) {
- DoSomethingAboutGreen();
- }
- else if ( IsBlue( color) ) {
- DoSomethingAboutBlue();
- }
- else return;
- }
- }
- void DoSomethingB( string color ) {
- if ( IsRed( color ) ) {
- for ( int i = 0; i < 5; ++i ) {
- DoSomethingAboutRed();
- }
- }
- else if ( IsGreen( color ) ) {
- for ( int i = 0; i < 5; ++i ) {
- DoSomethingAboutGreen();
- }
- }
- else if ( IsBlue( color) ) {
- for ( int i = 0; i < 5; ++i ) {
- DoSomethingAboutBlue();
- }
- }
- else return;
- }
- // 使用函数指针作为参数,默认参数为&IsBlue
- void DoSomethingC( void (*DoSomethingAboutColor)() = &DoSomethingAboutBlue ) {
- for ( int i = 0; i < 5; ++i )
- {
- DoSomethingAboutColor();
- }
- }
可以看到在DoSomethingA函数中,每次循环都需要判断一次color的值,这些属于重复判断;在C++编写程序中,for 循环重复写了三次,代码不够精练。如果我们在这里使用函数指针,就可以只判断一次color的值,并且for 循环也只写一次,DoSomethingC给出了使用函数指针作为函数参数的代码,而DoSomethingD给出了使用string作为函数参数的代码。