舉例說(shuō)明C++編寫(xiě)程序
進(jìn)行C++編寫(xiě)程序時(shí),你經(jīng)常需要在一個(gè)函數(shù)中調(diào)用其他函數(shù),此時(shí)就會(huì)考慮到使用函數(shù)指針,一個(gè)函數(shù)可以調(diào)用其他函數(shù)。在設(shè)計(jì)良好的程序中,每個(gè)函數(shù)都有特定的目的,普通函數(shù)指針的使用。
首先讓我們來(lái)看下面的一個(gè)例子:
- #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;
- }
- // 使用函數(shù)指針作為參數(shù),默認(rèn)參數(shù)為&IsBlue
- void DoSomethingC( void (*DoSomethingAboutColor)() = &DoSomethingAboutBlue ) {
- for ( int i = 0; i < 5; ++i )
- {
- DoSomethingAboutColor();
- }
- }
可以看到在DoSomethingA函數(shù)中,每次循環(huán)都需要判斷一次color的值,這些屬于重復(fù)判斷;在C++編寫(xiě)程序中,for 循環(huán)重復(fù)寫(xiě)了三次,代碼不夠精練。如果我們?cè)谶@里使用函數(shù)指針,就可以只判斷一次color的值,并且for 循環(huán)也只寫(xiě)一次,DoSomethingC給出了使用函數(shù)指針作為函數(shù)參數(shù)的代碼,而DoSomethingD給出了使用string作為函數(shù)參數(shù)的代碼。