【问题标题】:Invalid Lvalue, pointer to function also, whats the use of this? Its much simpler to call the function左值无效,函数指针也一样,这个有什么用?调用函数要简单得多
【发布时间】:2012-09-12 07:15:40
【问题描述】:

所以我正在练习指向函数的指针,并尝试制作这个简单的程序,这是它的一个 sn-p。在分配地址时,它仍然给我一个错误“无效的左值”。例如,funcptr = &addnum。我也忍不住想知道这个有什么用?调用函数是不是简单多了?还是我误会了什么

#include <stdio.h>
int arithnum(int base);
int addnum(int base,int new);
int subnum(int base,int new);
int mulnum(int base,int new);
int divnum(int base,int new);
typedef int *ptrdef(int,int);
int arithnum(int base)
{
    char operator;
    int operand;
    ptrdef funcptr;
    printf("Enter operator: ");
    scanf("\n%c",&operator);
    printf("Enter second operand: ");
    scanf("%d",&operand);
    switch(operator)
    {
        case '+':
            funcptr = &addnum;
            break;
        case '-':
            funcptr = &subnum;
            break;
        case '*':
            funcptr = &mulnum;
            break;
        case '/':
            funcptr = &divnum;
            break;
    }
    return funcptr(base,operand);
}

【问题讨论】:

标签: c pointers function-pointers lvalue


【解决方案1】:

ITYM

typedef int (*ptrdef)(int,int);

因为您的版本是一个返回 int * 的函数,而您想要一个返回 int 的函数指针。


只是提示:我知道以下不是常识,但我更喜欢typedef函数本身然后做

typedef int myfunc(int,int);
myfunc therealfunction; // bites me if I do a mistake
int therealfunction(int a, int b)
{
    // do stuff and
    return 42;
}
myfunc * funcptr = &therealfunction;

如果我不小心更改了therealfunction 的声明,就会被错误而不是警告所困扰。

【讨论】:

  • 谢谢哥们!!我现在明白了,但是我的第二个问题呢?这有什么用?调用函数要简单得多..
  • 通常说的用途是决定一次做什么,以后再做。这样做,您可以 e. G。创建作业队列系统,或数组中的函数表,将索引(本质上是 int)映射到要执行的函数。
【解决方案2】:

更改您的类型定义。

变化:

typedef int *ptrdef(int,int);

typedef int (*ptrdef)(int,int);

回答您的其他问题/陈述:“函数指针似乎没用”: 在您的示例中,它们的使用是微不足道的,但更有用的示例是 C++ 中的 vtables。函数指针允许基类定义函数的签名,然后子类可以用自己的实现替换这些函数指针,从而改变对象对函数的响应方式。

您还可以在 COM 模型 API 中使用它们,其中主应用程序与插件动态链接,并且它们的插件返回所请求接口的函数指针结构。

【讨论】:

  • 我很确定你必须这样做,互联网上的教程是这样说的。还有K&R
  • 如果你有一个无效的左值,改变右边的东西是没有用的。在这种情况下,funcptr 是错误的。看我的回答。
  • 您也不必获取地址或尊重 funcptr。 funcptr = divnumfuncptr(base,operand) 编译得很好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-10
  • 1970-01-01
  • 2020-01-12
  • 1970-01-01
  • 1970-01-01
  • 2014-07-26
相关资源
最近更新 更多