我之前从未在c ++中看到过这样的语法:
typedef int (callback)(int);
Run Code Online (Sandbox Code Playgroud)
这究竟是什么意思?我只是发现如果我创建一个声明
callback a;
Run Code Online (Sandbox Code Playgroud)
它的效果与前向函数声明非常相似.
下面是我写的代码
#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;
}
Run Code Online (Sandbox Code Playgroud)
您可以使用
typedef int (*callback)(int);//this is very common to use
Run Code Online (Sandbox Code Playgroud)
在此代码中,但如果我们将其更改为
typedef int (callback)(int); //I'm puzzled by this !
Run Code Online (Sandbox Code Playgroud)
这也会得到相同的结果!
我知道typedef int (*callback)(int) 并且 typedef int (callback)(int)
是两个完全不同的东西.
Naw*_*waz 11
因为在参数声明中,函数类型被调整为成为指向函数类型的指针.
typedef int type(int);
typedef int (*type)(int);
Run Code Online (Sandbox Code Playgroud)
第一个typedef定义一个被调用的类型function-type,而第二个typedef定义一个被调用的类型pointer-to-function-type.在参数声明中,函数类型被调整为成为函数类型的指针.
§13.1/ 3(C++ 03)说,
仅在那一个中不同的参数声明是函数类型而另一个是指向相同函数类型的指针是等效的.也就是说,调整函数类型以成为函数类型的指针(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())
]
Run Code Online (Sandbox Code Playgroud)
假设你有一个typedef,定义如下:
typedef void funtype();
Run Code Online (Sandbox Code Playgroud)
然后你可以用它来定义成员函数:
struct A
{
//member function declaration.
funtype f; //equivalent to : void f();
};
void A::f() //definition
{
std::cout << "haha" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
测试代码:
int main() {
A a;
a.f(); //call member function
}
Run Code Online (Sandbox Code Playgroud)
输出:
haha
Run Code Online (Sandbox Code Playgroud)
在线演示:http://ideone.com/hhkeK
| 归档时间: |
|
| 查看次数: |
533 次 |
| 最近记录: |