cppTest-3.0:指針相關-3(指針與函數)

/**
 *cppTest-3.0:指針相關-3(指針與函數)
 *
 *author 煒sama
 */
#include<iostream.h>
int SumArray(int arr[],int n);
void fun();
void main()
{
	static int a[3][4]={1,3,5,7,9,11,13,15,17,19,21,23};
	int *p,total1,total2;
	int (*pt)(int *,int); // pt與SumArray形式應保持一致
	pt=SumArray;//賦值到函數指針時不能帶參數!
	p=a[0];
	total1=SumArray(p,12);
	total2=(*pt)(p,12);//成功,教程上推薦的方法
	//total2=*pt(p,12);//編譯錯誤,錯誤的調用方法
	//total2=pt(p,12);//成功
	cout<<"total1="<<total1<<", total2="<<total2<<endl;
	
	void (*pFun)();
	pFun=fun;

	//*pFun();//編譯錯誤,錯誤的調用方法
	//pFun;//沒反應,錯誤的調用方法
	pFun();//成功
	//(*pFun);//沒反應,錯誤的調用方法
	(*pFun)();//成功,教程上推薦的方法
}
int SumArray(int arr[],int n)
{
	int i,sum=0;
	for(i=0;i<n;i++) sum=sum+arr[i];
		return sum;
}
void fun(){
	cout<<"無參無返回值fun"<<endl;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章