注册 登录
编程论坛 C++教室

求助

lixingang2008 发布于 2008-07-16 10:42, 456 次点击
指针:
int a=5;
int* p=0;
p=&a;
你们谁能帮我举个指针函数,函数指针的例子。
1 回复
#2
zjl1382008-07-16 12:31
指针函数是指带指针的函数,即本质是一个函数。
其定义格式如下所示:
返回类型标识符 *返回名称(形式参数表){ 函数体; }
for example:
#include<iostream>
using namespace std;
float *find(float(*pionter)[4],int n)//定义指针函数
{
    float *pt;
    pt=*(pionter+n);
    return pt;
}
int main()
{
    static float score[][4]={{60,70,80,90},{56,89,34,45},{34,23,56,45}};
    float *p;
    int i,m;
    cout<<"Enter the number to be found:";
    cin>>m;
    cout<<"the score of NO.%d are:\n";
    p=find(score,m);
    for (i=0;i<4;i++)
        printf("%5.2f\t",*(p+i));
    return 0;
}




函数指针是指向函数的指针变量。
“函数指针”本身首先应是指针变量,只不过该指针变量指向函数。这正如用指针变量可指向整型变量、字符型、数组一样,这里是指向函数.
#include<iostream>
using namespace std;
void func1();
void func2();
int main(void)
{
    void(*funcp)();   //declare a pointer to a function
    //put an address in the pointer,and call the function through the pointer
    funcp = func1;
    (*funcp)();
    funcp = func2;
    (*funcp)();
    return 0;
}
void func1()
{
    cout<<"Func1"<<endl;
}
void func2()
{
    cout<<"Func2"<<endl;
}
1