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

冷暖自知 提交于 2019-12-24 14:03:44

问题


A quick question I hope. I would like to know why the line commented out below 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;
}

回答1:


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

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


来源:https://stackoverflow.com/questions/5962358/definition-and-assignment-of-pointers-to-functions-at-global-and-local-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!