c++ - typedef decltype 函数指针未返回正确的输出 (cout)
问题描述
我在使用 decltype 创建指向“foo”的 typedef 函数指针时遇到问题。printf 有效,但有警告:warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘bar {aka int (*)(int)}’ [-Wformat=]
并且 cout 显示“1”。在函数指针方面,我有点像新手,所以我真的不知道发生了什么。有人可以在这里帮助我吗?
#include <iostream>
int foo(int a) {
return a;
}
int main() {
typedef decltype(&foo) bar;
printf("printf: %d\n", (*bar(70))); //work with a warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘bar {aka int (*)(int)}’ [-Wformat=]
std::cout << "cout: " << (*bar(80));//displays "cout: 1" for some reason
return 0;
}
解决方案
您必须创建类型变量bar
并使用foo
地址对其进行初始化。
因为()
优先级高于*
,所以你必须使用括号(*var)(80)
来取消引用指向函数的指针,之后你可以调用它:
typedef decltype(&foo) bar;
bar b = &foo;
printf("printf: %d\n", ((*b)(70))); //work with a warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘bar {aka int (*)(int)}’ [-Wformat=]
std::cout << "cout: " << ((*b)(80));//displays "cout: 1" for some reason
要不就:
b(80)
没有明确的取消引用。
推荐阅读
- reactjs - React Ag 网格 expandAll 在企业中
- sql - 当列数未知时,如何在多个列上连接两个表(pyspark)
- r - 为什么 lapply 不转发其他参数?
- python-3.x - Django ImageField.url 返回带有过期查询字符串而不是普通 url 的 URL
- python - 使用 Pandas 和 Flask 输出不带省略号的完整字符串
- oracle - 与 oracle 数据库连接时出现 Spring 错误(ORA-12505,TNS:listener 目前不知道连接描述符中给出的 SID)
- css - 如何根据孩子的 div 的数量将宽度自动调整为父母的宽度大小
- reactjs - 反应路由器 DOM 问题
- angular - 离子科尔多瓦角度构建未针对正确的环境
- angular - 使用 swarm-js 的 Angular Universal 问题的服务器端渲染 (SSR)