C++中函式指標以及函式指標陣列的簡單使用
阿新 • • 發佈:2019-01-04
最近複習C++,突然看到函式指標,由於自己上學期C++學習的比較水,所以在這裡專門總結一下。 與普通的指標相似,指向函式的指標包含記憶體中該函式的地址。對比陣列,陣列名實際是陣列的第一個元素在記憶體中的地址。類似的,函式名實際上是這個函式程式碼在記憶體中的開始地址。另外,一定要注意,函式指標要用 type (*FunctionPtr) 的形式,不要寫成 type *FunctionPtr的形式,後者表示返回一個所指型別的指標。
上程式碼:
include <iostream>
using namespace std;
void Function();
void testFunction(void (*)());
int main()
{
testFunction(Function );
return 0;
}
void Function()
{
cout<<"你好!";
}
void testFunction(void (*Function)())
{
(*Function)();//一定要注意,這裡的()不要省略!
}
函式指標陣列理解起來就比較容易,但是要注意,陣列所指向的所有函式都要有相同型別的返回值和相同的引數型別。
看程式碼:
include <iostream>
using namespace std;
void function0(int);
void function1(int );
void function2(int);
int main()
{
void (*Function[3])(int) = {function0,function1,function2};
int choice;
cout<<"enter a number between 0 to 2,and you can enter 3 to end"<<endl;
cin>>choice;
while(choice>=0&&choice<=2)
{
(*Function[choice])(choice);
cout <<"continue"<<endl;
cin>>choice;
}
return 0;
}
void function0(int a)
{
cout<<"You chose function0 and entered "<<a<<endl;
}
void function1(int a)
{
cout<<"You chose function1 and entered "<<a<<endl;
}
void function2(int a)
{
cout<<"You chose function2 and entered "<<a<<endl;
}