C++傳遞函數指針
C++允許將一個指針傳遞給函數。要做到這一點,隻需聲明函數參數作為指針類型。
下麵我們通過一個unsigned long指針的函數並更改,其反射回來在調用函數的函數裡麵的值一個簡單的例子:
#include <iostream> #include <ctime> using namespace std; void getSeconds(unsigned long *par); int main () { unsigned long sec; getSeconds( &sec ); // print the actual value cout << "Number of seconds :" << sec << endl; return 0; } void getSeconds(unsigned long *par) { // get the current number of seconds *par = time( NULL ); return; }
當上述代碼被編譯和執行時,它產生了以下結果:
Number of seconds :1294450468
它可以接受指針函數,還可以接受數組,如下麵的例子所示:
#include <iostream> using namespace std; // function declaration: double getAverage(int *arr, int size); int main () { // an int array with 5 elements. int balance[5] = {1000, 2, 3, 17, 50}; double avg; // pass yiibaier to the array as an argument. avg = getAverage( balance, 5 ) ; // output the returned value cout << "Average value is: " << avg << endl; return 0; } double getAverage(int *arr, int size) { int i, sum = 0; double avg; for (i = 0; i < size; ++i) { sum += arr[i]; } avg = double(sum) / size; return avg; }
當上述代碼被編譯在一起並執行時,它產生了以下結果:
Average value is: 214.4