我以前从未在 c++ 中看到过这样的语法:
typedef int (callback)(int);
这到底是什么意思?我只是发现如果我创建一个语句
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);//this is very common to use
在这段代码中,但是如果我们把它改成
typedef int (callback)(int); //I'm puzzled by this !
这也会得到相同的结果!
我知道 typedef int (*callback)(int)
和 typedef int (callback)(int)
是两种完全不同的东西。
最佳答案
因为在参数声明中,function-type被调整为pointer-to-function-type.
typedef int type(int);
typedef int (*type)(int);
第一个 typedef 定义了一个称为 function-type
的类型,而第二个 typedef 定义了一个称为 pointer-to-function-type
的类型。在参数声明中,function-type被调整为指向函数类型的指针。
§13.1/3 (C++03) 说,
Parameter declarations that differ only in that one is a function type and the other is a pointer to the same function type are equivalent. That is, the function type is adjusted to become a pointer to function type (8.3.5).
[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,定义为:
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
关于c++ - typedef 的奇怪用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7557968/