开发者

Definition and Assignment of Pointers to functions at global and local scope

A quick question I hope. I would like to know why the line commented out belo开发者_JAVA技巧w causes an error when placed at the global level while it works fine when placed inside the main function?

Many Thanks

#include <iostream>
using namespace std;
bool compare(const int &v1, const int &v2)  {
    if (v1 < v2) { 
        return true;
    } else {
        return false;
    }
}


bool (*pf5)(const int &v1, const int &v2);
//pf5 = compare;


int main() {
    int v1 = 5;
    int v2 = 6;
    pf5 = compare;

    bool YesNo1 = compare(v1, v2);
    cout << YesNo1 << endl;
    bool YesNo3 =pf5(v1, v2);
    cout << YesNo3 << endl;

    return 1;
}


You can't perform assignments except inside functions. You can however perform initialisations:

bool (*pf5)(const int &v1, const int &v2) = compare;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜