根据MSDN,typedef语法是:
typedef type-declaration同义词;
很容易:
typedef int MY_INT;
Run Code Online (Sandbox Code Playgroud)
但是成员函数指针typedef如何符合这条规则呢?
typedef int (MyClass::*MyTypedef)( int);
Run Code Online (Sandbox Code Playgroud)
100%混淆 - 同义词(MyTypedef
)在中间?
有人可以解释从MSDN的非常容易理解的语法格式到上面的typedef的反向/随机/前/上/混合语法的逻辑步骤是什么?
*编辑感谢所有快速答案(和我的帖子的美化):)
Naw*_*waz 38
同义词(MyTypedef)位于中间?
它不在中间.暂时忘记成员函数,看看如何定义函数指针:
int (*FuncPtr)(int);
Run Code Online (Sandbox Code Playgroud)
这就是你如何键入它:
typedef int (*FuncPtr)(int);
Run Code Online (Sandbox Code Playgroud)
简单!唯一的区别是,在typedef FuncPtr
成为一个类型,而在指针声明中,FuncPtr
是一个变量.
同样的,
int (MyClass::*MyTypedef)( int); //MyTypedef is a variable
Run Code Online (Sandbox Code Playgroud)
而typedef为:
typedef int (MyClass::*MyTypedef)( int); //MyTypedef is a type!
Run Code Online (Sandbox Code Playgroud)
kfs*_*one 17
值得注意的是,从C++ 11开始,您可以将此表达式编写为更清晰的using
语句:
using MyTypedef = int (MyClass::*)(int);
Run Code Online (Sandbox Code Playgroud)
ybu*_*ill 10
如何定义指向成员函数的指针?像这样:
int (A::*variableName)(int);
Run Code Online (Sandbox Code Playgroud)
要使它成为typedef,只需添加一个typedef:
typedef int (A::*typedefName)(int);
Run Code Online (Sandbox Code Playgroud)
我知道你已经得到了答案,但想分享这个 - 它很方便:http : //www.cdecl.org。这是一个 C/C++ 声明 <-> 英文翻译器。只需输入
将 x 声明为指向 A 类函数 (int) 成员的指针,返回 char
你得到char (A::*x)(int )
. 或者玩弄声明,看看你是否得到了你想要的。
使用成员函数指针的语法必须(假设a
是 class 的一个实例A
):
下面是一个玩具示例。你可以玩它。
#include <stdio.h>
#include <stdlib.h>
class A;
typedef int (A::*F)(double);
class A {
public:
int funcDouble(double x) { return (int)(x * 2.0); }
int funcTriple(double x) { return (int)(x * 3.0); }
void set(int a) {
if (a == 2) {
this->f_ = &A::funcDouble;
} else if (a == 3) {
this->f_ = &A::funcTriple;
} else {
this->f_ = NULL;
}
}
public:
F f_;
};
int main(int argc, char *argv[]) {
A a;
a.set(2);
F f = &A::funcDouble;
printf("double of 1 = %d\n", (a.*f)(1));
// Below is equivalent to:
// F f2 = a.f_;
// printf("double of 1 = %d\n", (a.*f2)(1));
printf("double of 1 = %d\n", (a.*(a.f_))(1));
a.set(3);
printf("triple of 1 = %d\n", (a.*(a.f_))(1));
return 0;
}
Run Code Online (Sandbox Code Playgroud)