问题
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