這篇文章是我看Siki學院學習的筆記,學習的地址如下:
http://www.sikiedu.com/my/course/518
因本人才疏學淺,如有錯誤之處,還請見諒
定義
與數據項;類似,函數也有地址,函數的地址是存儲其機器語言代碼內存的開始地址.可以將地址作爲函數的參數,從而使第一個函數能夠找到第二個函數,並運行它.
函數指針指向的是函數而不是對象
想要聲明一個可以指向的是函數而非對象
想要聲明一個可以指向函數的指針,只需要用指針替換函數名即可
下面是一個例子
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main(void){
bool lengthCompare(const string &,const string &); //函數
bool (*pf)(const string &,const string&); //函數指針
return 0;
}
pf是一個指向函數的指針,其中該函數的參數是兩個const string的引用,返回值是布爾類型
注意:
*pf的兩端的括號必不可少,如果省略括號,就變成了一個返回值爲bool指針的函數,而不是指針函數的指針.
當我們把函數名作爲一個值使用時,該函數自動的轉換成指針,還可以直接使用指向函數的指針調用該函數
#include<iostream>
#include<string>
#include<vector>
#include <iterator>
using namespace std;
bool lengthCompare(const string &,const string &); //普通的函數
void display(const string &s1,const string &s2,bool(*p)(const string &,const string &));
int main(void){
string name1="Sandy";
string name2="Jane";
bool res=lengthCompare(name1,name2);
bool (*pf)(const string&,const string&); //函數指針
pf = lengthCompare; //讓函數指針,指向函數
display(name1,name2,pf);
return 0;
}
bool lengthCompare(const string &s1,const string &s2){
return s1.size()>s2.size();
}
//讓這個函數指針,當成一個參數傳遞給另外一個函數
void display(const string &s1,const string &s2,bool(*p)(const string &,const string &)){
if(p(s1,s2)==true){
cout<<s1<<"的長度大於"<<s2<<endl;
}
else{
cout<<s1<<"的長度小於"<<s2<<endl;
}
}