指向全局和局部范围函数的指针的定义和赋值 [英] Definition and Assignment of Pointers to functions at global and local scope

查看:167
本文介绍了指向全局和局部范围函数的指针的定义和赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望有一个快速问题。我想知道为什么下面注释掉的行会导致一个错误,当放置在全局级别,当它工作正常,当放置在main函数内时。

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?

很感谢

#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;

这篇关于指向全局和局部范围函数的指针的定义和赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆