typedef的奇怪用法 我以前从未见过这样的C++语法: typedef int (callback)(int);

typedef的奇怪用法 我以前从未见过这样的C++语法: typedef int (callback)(int);,c++,typedef,C++,Typedef,这到底意味着什么?我发现如果我创建一个语句 callback a; 它的效果非常类似于前向函数声明 下面是我写的代码 #include<cstdio> int callbackfunc(int i) { printf("%d\n",i); return i*i; } // you can also use typedef int (callback)(int) here! typedef int (*callback)(int); void func(ca

这到底意味着什么?我发现如果我创建一个语句

  callback a;
它的效果非常类似于前向函数声明

下面是我写的代码

#include<cstdio>

int callbackfunc(int i)
{
    printf("%d\n",i);
    return i*i;
}

// you can also use typedef int (callback)(int) here!
typedef int (*callback)(int);

void func(callback hook)
{
    hook(hook(3));
}

int main()
{
    func(callbackfunc);
    getchar();
        return 0;
}
在本代码中,但如果我们将其更改为

typedef int (callback)(int); //I'm puzzled by this !
这也会得到同样的结果

我知道
typedefint(*callback)(int)
typedefint(callback)(int)


是两种完全不同的东西。

这是因为函数在必要时隐式成为函数指针。这些是相同的:

func(callbackfunc);

func(&callbackfunc);

这是因为在参数声明中,函数类型被调整为指向函数类型的指针

第一个typedef定义的类型称为
函数类型
,而第二个typedef定义的类型称为
指向函数类型的指针
。在参数声明中,函数类型被调整为指向函数类型的指针

§13.1/3(C++03)规定

参数声明的不同之处在于一个是函数类型,另一个是指向相同函数类型的指针,它们是等价的也就是说,将函数类型调整为指向函数类型(8.3.5)的指针。


函数类型独占使用的一个有趣示例 假设您有一个typedef,定义为:

typedef void funtype();
然后,您可以使用它将成员函数定义为:

输出:

haha

在线演示:

先生,你真的知道你的C++。我在那个链接找到了同样的问题->并且有一个很棒的答案。我可以建议。。。
[Example:
    void h(int());
    void h(int (*)()); // redeclaration of h(int())
    void h(int x()) { } // definition of h(int())
    void h(int (*x)()) { } // ill-formed: redefinition of h(int())
]
typedef void funtype();
struct A
{
   //member function declaration. 
    funtype f; //equivalent to : void f();
};

void A::f() //definition
{
  std::cout << "haha" << std::endl;
}
int main() {
        A a;
        a.f(); //call member function
}
haha