【发布时间】:2011-11-17 18:35:09
【问题描述】:
在得到this question 的答复后,我发现有两种有效的方法来定义函数指针。
typedef void (Function) ();
typedef void (*PFunction) ();
void foo () {}
Function * p = foo;
PFunction q = foo;
我现在更喜欢Function * p 而不是PFunction q,但显然这不适用于指向成员的函数。考虑这个人为的例子。
#include <iostream>
struct Base {
typedef void (Base :: *Callback) ();
//^^^ remove this '*' and put it below (i.e. *cb)
Callback cb;
void go () {
(this->*cb) ();
}
virtual void x () = 0;
Base () {
cb = &Base::x;
}
};
struct D1 : public Base {
void x () {
std :: cout << "D1\n";
}
};
struct D2 : public Base {
void x () {
std :: cout << "D2\n";
}
};
int main () {
D1 d1;
D2 d2;
d1 .go ();
d2 .go ();
}
但如果我将其更改为新的首选样式:typedef void (Base :: Callback) () 和 Callback * cb,我会在 typedef 处收到编译器错误
成员“回调”的额外资格“Base::”
为什么不允许这样做?这仅仅是一个疏忽还是会导致问题?
【问题讨论】:
-
@Als 现在把
*从 typedef 中去掉,你就会明白他的意思了。 -
@Als,不是doesn't compile。
-
准确地说:
typedef void Function();定义了类型不带参数且不返回任何内容的函数的别名,注意其中没有指针那里的类型...该 typedef 定义了函数的签名,而不是指向具有该签名的函数的指针。
标签: c++ compiler-errors function-pointers typedef member-function-pointers