Mat*_*gan 7 c++ typedef function-pointers reference
会typedef int (&rifii) (int, int)用什么?
这个"声明"之前的typedef是什么?我想把它想象成这样
typedef (int (&rifii) (int, int)) [new name]
Run Code Online (Sandbox Code Playgroud)
但如果你这样做的话,[新名字]并不存在
typedef int INTEGER;
Run Code Online (Sandbox Code Playgroud)
类似的问题,以下语法:
typedef void (*PF) ();
PF edit_ops[ ] = { &cut, &paste, ©, &search };
PF file_ops[ ] = { &open, &append, & close, &write };
PF* button2 = edit_ops;
PF* button3 = file_ops;
button2[2]( );
Run Code Online (Sandbox Code Playgroud)
什么是typedef允许?它是否正在制作,因此您无需键入:
void (*PF) ();
(void (*PF) ()) edit_ops[ ] = { &cut, &paste, ©, &search };
(void (*PF) ()) file_ops[ ] = { &open, &append, & close, &write };
(void (*PF) ())* button2 = edit_ops;
(void (*PF) ())* button3 = file_ops;
Run Code Online (Sandbox Code Playgroud)
如果是这样,那么typedef的第二部分([你想要的])会发生什么:
typedef [what you have -- (FP)] [what you want]
Run Code Online (Sandbox Code Playgroud)
非常感谢对这个问题的澄清.
Sjo*_*erd 17
Typedef不起作用typedef [type] [new name].这个[new name]部分并不总是在最后.
你应该这样看:如果[some declaration]声明一个变量,typedef [same declaration]就会定义一个类型.
例如:
int x;声明一个名为x的类型为int的变量 - > typedef int x;
将类型x定义为int.struct { char c; } s;定义一个名为s的某个struct类型的变量 - > typedef struct { char c; } s;将type s定义为某种struct类型.int *p;声明一个名为p的变量,指向int的类型指针 - >
typedef int *p;将一个类型p定义为指向int的指针.并且:
int A[];声明一个名为A的整数数组 - >将typedef int A[];一个类型A声明为一个整数数组.int f();声明一个名为f - > typedef int f();的函数声明一个函数类型f,它返回一个int并且不带参数.int g(int);声明一个函数名g - > typedef int g(int);声明一个函数类型g作为返回一个int并取一个int.暂且不说:请注意,所有函数参数都在新名称之后!由于这些类型也很复杂,[新名称]之后可能会有很多文字.可悲的是,但这是真的.
但那些不是正确的函数指针,只是函数类型.我不确定C或C++中是否存在函数类型,但它在我的解释中作为中间步骤很有用.
要创建一个真正的函数指针,我们必须在名称中添加"*".遗憾的是,这有错误的优先顺序:
typedef int *pf();声明函数类型pf作为返回int*.糟糕,这不是预期的.所以使用()分组:
typedef int (*pf)(); 声明函数指针类型为pf,返回int并且不带参数.typedef int (&rf)(); 声明函数引用类型rf为返回int并且不带参数.现在让我们看一下您的示例并回答您的问题:
typedef int (&rifii) (int, int); 声明函数引用类型rifii为返回int并获取两个int参数.
显然(?)button2[2]( );会打电话copy();.
没有typedef的正确语法很难在没有编译器的情况下正确编写,即使使用编译器也难以阅读:
void (*edit_ops[])() = { &cut, &paste, ©, &search };
void (*file_ops[])() = { &open, &append, & close, &write };
void (**button2)() = edit_ops;
void (**button3)() = file_ops;
button2[2]( );
Run Code Online (Sandbox Code Playgroud)
这就是为什么每个人在使用函数指针时都更喜欢typedef.
阅读时,找到开始阅读的地方.尽可能多地阅读,但请观察()的分组.然后尽可能多地向左读,再次受限于分组().完成()内部的所有操作后,从右侧读取开始,然后向左侧读取.
适用于void (*edit_ops[])(),这意味着
对于专家:
为了使它更复杂,参数可以有名称(将被忽略),因此甚至可能很难找到从哪里开始解析!Eg typedef int (*fp)(int x);是有效的,就像typedef int (*fp)(int);Names甚至可以在它们周围有()一样:typedef int (*fp)(int (x));但正如我们所看到的,参数名称可以省略,所以即使允许以下内容:typedef int (*fp)(int ());.这仍然是一个函数指针,它采用单个int并返回一个int.如果您想让您的代码真的难以阅读......
| 归档时间: |
|
| 查看次数: |
2086 次 |
| 最近记录: |