首页 > 解决方案 > 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;
}

标签: c++

解决方案


您必须创建类型变量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)

没有明确的取消引用。

演示


推荐阅读