【问题标题】:typedef decltype function pointer not returning proper output (cout)typedef decltype 函数指针未返回正确的输出 (cout)
【发布时间】:2020-06-27 14:19:11
【问题描述】:

我在使用 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 不是函数指针,它是一个类型,bar(70) 是一个函数式类型转换。

标签: c++


【解决方案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)

没有显式取消引用。

Demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-28
    • 2020-01-12
    • 1970-01-01
    • 1970-01-01
    • 2011-05-16
    相关资源
    最近更新 更多