新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
舉例說明C++編寫程序
進(jìn)行C++編寫程序時,你經(jīng)常需要在一個函數(shù)中調(diào)用其他函數(shù),此時就會考慮到使用函數(shù)指針,一個函數(shù)可以調(diào)用其他函數(shù)。在設(shè)計良好的程序中,每個函數(shù)都有特定的目的,普通函數(shù)指針的使用。

創(chuàng)新互聯(lián)主營樂平網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營網(wǎng)站建設(shè)方案,重慶APP開發(fā),樂平h5微信小程序搭建,樂平網(wǎng)站營銷推廣歡迎樂平等地區(qū)企業(yè)咨詢
首先讓我們來看下面的一個例子:
- #include
- #include
- #include
- 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++編寫程序中,for 循環(huán)重復(fù)寫了三次,代碼不夠精練。如果我們在這里使用函數(shù)指針,就可以只判斷一次color的值,并且for 循環(huán)也只寫一次,DoSomethingC給出了使用函數(shù)指針作為函數(shù)參數(shù)的代碼,而DoSomethingD給出了使用string作為函數(shù)參數(shù)的代碼。
文章名稱:舉例說明C++編寫程序
URL鏈接:http://www.dlmjj.cn/article/djdeeee.html


咨詢
建站咨詢
