作者godfat (godfat 真常)
看板C_and_CPP
标题Re: [问题] 关於 signal()
时间Sat Feb 4 18:37:48 2006
: : void (*test1(int in))(int){
: 请问这行的宣告, 是什麽意思呢?
test1 是一个 function, 他吃一个 int 参数
// test1(5);
// => call test1
传回值是一个 function pointer, 型别是:
void (*)(int), 也就是没有传回值,吃一个 int 参数
// void (*pf)(int) = test1(5);
// => pf 指向 test1 的传回值
: : printf("test1 is called by %d\n", in);
: : return &test2;
: 我如果把这里改成
: return;
: 他会告诉我 " 程式记忆体区段错误 "
嗯?我会编译错误说
应该没道理可以编译,型别会不相符
: 但是小弟实在是对这一段 code 不是很了解.
: test(5)(10) 这样子的写法, 是什麽意思呢?
void (*pf)(int) = test1(5);
pf(10);
这样会不会比较好懂? :)
简单说就是我直接呼叫他传回的 function
没有拿一个变数去把他存起来
假使我写成这样:(不要头昏喔 XD)
void (*(*test0(int in))(int))(int){
printf("test0 is called by %d\n", in);
return &test1;
}
然後改成这样 call:
test0(5)(10)(15);
/* output result:
test0 is called by 5
test1 is called by 10
test2 is called by 15
*/
我的 test0 传回一个 function pointer 指向一个传入是 int,
传出是一个 function pointer, 这个 f.. p.. 的传入是 int,
传出是一个 f.. p.. 指向一个传入是 int,
传出是 void 的 function
呃,我想我中文表达得很差,建议看 code 测试几次比较容易懂
总之就是一个 pf 串一个 pf 就是了
如果能改成 functor 来看的话会更容易懂(如果是 C++ 的话)
void test2(int in){
}
Functor test1(int in){
return &test2;
}
Functor test0(int in){
return &test1;
}
test0(5)(10)(15);
// 等同於:
Functor f1 = test0(5);
Functor f2 = f1(10);
f2(15);
// 等同於:
void (*(*pf1)(int))(int) = test0(5);
void (*pf2)(int) = pf1(10);
pf2(15);
: 翻了一两本书, 好像都没有提到相关的写法 Orz .....
我想这些东西都是技巧,多练习比较容易熟悉
你还没贴这篇之前我也没想过这样玩 XD
--
--
※ 发信站: 批踢踢实业坊(ptt.cc)
※ 编辑: godfat 来自: 220.132.128.238 (02/04 18:44)
1F:推 drkkimo:解释的很清楚呀 02/04 19:50
2F:推 lightspeed:推荐这篇文章 02/04 21:05
3F:推 inses:推,其实重点就是把return type抓出来,一层层颇析 02/04 21:17
4F:推 chy168:Cool~ 我懂了, 感谢您~ :pp 02/04 22:52