C++primer第五版 函式指標
阿新 • • 發佈:2018-12-12
指標在c++中既是重點又是難點,最開始學指標的時候就已經很繞了,然後接觸函式指標的時候,就徹底暈了。很多書在編寫函式指標這一塊時講得並不清楚,這裡推薦一篇總結函式指標還不錯的部落格,可以學習一下
函式指標指向的是函式而非物件。和其他指標一樣,函式指標指向某種特定型別,函式的型別由它的返回型別和形參型別共同決定,與函式名無關。
這裡,我先以C++primer第五版6.7節的幾個練習為例編寫程式碼熟悉函式指標的使用。具體要求如下:
1. 編寫函式的宣告,令其接受兩個int形參並且返回型別也是int;然後宣告一個vector物件,令其元素是指向該函式的指標。 2. 編寫4個函式,分別對兩個int值執行加、減、乘、除運算,在建立的vector物件中儲存指向這些函式的指標。 3. 呼叫vector物件中的每個元素並輸出其結果。
先附上程式碼
// primer_6_7.cpp : Defines the entry point for the application. // 編寫函式的宣告,令其接受兩個int形參並且返回型別也是int;然後宣告一個vector物件,令其元素是指向該函式的指標。 // 編寫4個函式,分別對兩個int值執行加、減、乘、除運算,在建立的vector物件中儲存指向這些函式的指標。 // 呼叫vector物件中的每個元素並輸出其結果。 #include "stdafx.h" #include<iostream> #include<vector> using namespace std; int main() { typedef int(PF)(int,int); //使用類型別名,將PF定義成函式型別 PF *result; //顯式地指定返回型別是指向函式的指標 int fun_add(int,int); //函式宣告,對兩個int值執行加法運算 int fun_sub(int,int); //函式宣告,對兩個int值執行減法運算 int fun_multi(int,int); //函式宣告,對兩個int值執行乘法運算 int fun_div(int,int); //函式宣告,對兩個int值執行除法運算 vector<int> vec; //宣告一個vector物件 int flag=1; //讓使用者選擇是否繼續計算而定義的一個標誌 int temp; //儲存計算結果的變數 int num_a,num_b; //使用者輸入的兩個數 while(flag) //flag為1意味著使用者希望繼續計算,為0意味著使用者希望退出 { cout << "input two numbers: " << endl; //讓使用者輸入兩個數 cin >> num_a >> num_b; cout << "choose a operation: (a b c d)" << endl; //讓使用者選擇進行哪種操作 cout << "(a) add\t(b) substraction" << endl; cout << "(c) multiplication\t(d) divide" << endl; char choose; cin >> choose; switch(choose) //對不同的選擇進行不同的操作 { case 'a': result=fun_add; temp=result(num_a,num_b); vec.push_back(temp); cout << num_a << " + " << num_b << " = " << *(vec.end()-1) << endl; //輸出結果,*(vec.end()-1)表示vec容器中最後新增進來的值 break; case 'b': result=fun_sub; temp=result(num_a,num_b); vec.push_back(temp); cout << num_a << " - " << num_b << " = " << *(vec.end()-1) << endl; break; case 'c': result=fun_multi; temp=result(num_a,num_b); vec.push_back(temp); cout << num_a << " * " << num_b << " = " << *(vec.end()-1) << endl; break; case 'd': result=fun_div; temp=result(num_a,num_b); vec.push_back(temp); cout << num_a << " / " << num_b << " = " << *(vec.end()-1) << endl; break; } cout << "go on? y or n" << endl; //讓使用者選擇是否繼續計算 char y_or_n; cin >> y_or_n; if(y_or_n=='y') flag=1; if(y_or_n=='n') flag=0; } system("pause"); return 0; } //定義加、減、乘、除函式 int fun_add(int a,int b) { return (a+b); } int fun_sub(int a,int b) { return a-b; } int fun_multi(int a,int b) { return a*b; } int fun_div(int a,int b) { return a/b; }
為了與使用者的互動性更好,我打印出了加、減、乘、除四種數學運算的操作選項讓使用者選擇一種操作;然後還定義了一個標誌變數flag,讓使用者選擇繼續計算或者退出計算。這些考慮是為了讓程式更實用,但是本篇部落格的根本目的還是聯絡函式指標的使用哈。
首先看下面一行程式碼
typedef int(PF)(int,int); //使用類型別名,將PF定義成函式型別
這裡是使用類型別名,定義一個函式型別
PF *result; //顯式地指定返回型別是指向函式的指標
這裡定義一個函式指標
然後根據使用者選擇的操作,在case中將不同的函式地址賦給該指標,再用指標進行函式呼叫,最後輸出計算結果。
效果如下: