您的位置:首页 > 其它

函数指针.回调函数.学习

2010-12-10 17:12 337 查看
最近看Android代码,发现很多回调函数的使用,由于本来对回调函数的不熟悉,感觉很生涩.于是自己写了几行代码来熟悉熟悉.

回调函数首先就得有一个函数指针.

typedef void (*callback_fun)(char *ptr);




其次,得有供函数指针指向的函数

void output_int(char *x)
{
    cout << "output_int:" << x << endl;
}


void output_double(char *y)
{
    cout << "output_double" << y << endl;
}


这里其实最开始遇到了一点问题,呵呵,我最初定义的参数类型为void,因为我希望代码能够更具通用性,但是后来发现,函数指针指向的函数的参数类型必须匹配才行.



函数指针与函数都有了,那么还得有将函数指针与函数联系起来的地方,如果直接在main函数里赋值,感觉太简单了,没有挑战性,于是我再写了一个函数

template<typename T>
bool QueryCallback(callback_fun &cb,T temp)//这里得注意,回调函数的函数指针必须得传"引用"传地址会报错,而如果作为普通参数传进来,会因为作用域的问题,在函数结束后被销毁.其实这里存有疑惑,为什么不能传指针,难道说typedef的类型,在C++里面只能传引用?
{
    float result = temp - (int)temp;
    if(result > 0.000001)
    {
        cb = output_double;
        return true;
    }
    else if( result < 0.000001 )
    {
        cb = output_int;
        return true;
    }
    else
    {
        return false;
    }
}




main函数就很简单了

int main()
{
    char temp[256];
    int a = 20;
    callback_fun cb;
    if(QueryCallback(cb,a)==false)
    {
        return -1;
    }
    sprintf(temp,"%d",a);
    cb(temp);
    double b = 33.333333;
    if(QueryCallback(cb,b)==false)
    {
        return -1;
    }
    sprintf(temp,"%f",b);
    cb(temp);
    return 0;
}




主要遇到几个问题,一个是函数指针定义的时候参数必须与其欲指向的函数接受的参数类型相同.第二个,typedef的函数指针作为参数传递时,需要传递引用.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: