c++ - 如何解决函数指针的这个错误?
问题描述
在一个程序中,一个指针被声明为函数 (p),该函数被初始化为函数 (add)
我试图阅读与函数指针相关的所有概念。但我无法解决它请帮我解决这个程序没有任何错误。
#include <stdio.h>
#include <iostream>
using namespace std;
int add(int n1, int n2)
{
return n1 + n2;
}
int *functocall(int,int);
int caller(int n1, int n2, int(*functocall)(int, int))
{
return (*functocall)(n1, n2);
}
int main()
{
int a, b, c;
cin >> b >> c;
int (*p)(int,int)=&add;
a=caller(b,c,(*functocall)(b,c));
printf("%d",a);
return 0;
}
如果输入是 20 70 输出必须是 90
解决方案
(*functocall)(b,c)
不符合您的预期,您正在尝试调用functocall
. (注意,它functocall
被声明为一个函数,它接受两个int
s 并返回一个int*
。)
您应该将函数指针本身传递给caller
,例如
a = caller(b, c, p);
或者
a = caller(b, c, &add);
推荐阅读
- neovim - neovim 错误 Windows 10 UltiSnips 与 python 3
- python - 在python中将数组分配给JSON键会创建无效的JSON
- java - 如何在 iText 5 中显示 WYSIWYG 字段?
- awk - 在两个模式之间加入
- java - java - 如何从Java中REST Web服务的服务层的单元测试中调用@RestControllerAdvice类?
- java - 使用给定的字符串,删除括号内的任何内容
- html - 背景剪辑:填充框不起作用(背景)
- c++ - VS Code 根本不显示局部变量
- css - 组合共享一个类的 2 个菜单 ID 元素,并为该类添加不同的背景
- php - 如果值包含 (,) 在 Php 中如何创建新行