提问者:小点点

typedef decltype函数指针未返回正确的输出(cout)


我在使用decltype创建指向“foo”的typedef函数指针时遇到了一个问题。 printf可以工作,但有警告:警告:格式“%d”需要类型为“int”的参数,但参数2的类型为“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;
}

共1个答案

匿名用户

您必须创建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)

而无需显式取消引用。

演示