在C/C++中,如果我有以下功能:
void foo();
void bar(void (*funcPtr)());
Run Code Online (Sandbox Code Playgroud)
这两个电话之间有区别吗:
bar(foo);
bar(&foo);
Run Code Online (Sandbox Code Playgroud)
?
有趣的是,将函数名称用作函数指针等同于将address-of运算符应用于函数名称!
这是一个例子.
typedef bool (*FunType)(int);
bool f(int);
int main() {
FunType a = f;
FunType b = &a; // Sure, here's an error.
FunType c = &f; // This is not an error, though.
// It's equivalent to the statement without "&".
// So we have c equals a.
return 0;
}
Run Code Online (Sandbox Code Playgroud)
使用这个名称是我们在数组中已经知道的.但是你不能写出类似的东西
int a[2];
int * b = &a; // Error!
Run Code Online (Sandbox Code Playgroud)
这似乎与该语言的其他部分不一致.这个设计的基本原理是什么?
这个问题解释了这种行为的语义及其工作原理.但是我对这种语言设计的原因很感兴趣.
更有趣的是,当用作参数时,函数类型可以隐式转换为指向自身的指针,但在用作返回类型时不会转换为指向自身的指针!
例:
typedef bool FunctionType(int);
void g(FunctionType); // Implicitly converted to void g(FunctionType …Run Code Online (Sandbox Code Playgroud) 也许这是一个愚蠢的问题,但我是红宝石的新手,我用Google搜索,发现这些:
proc=Proc.new {|x| deal_with(x)}
a_lambda = lambda {|a| puts a}
Run Code Online (Sandbox Code Playgroud)
但我想要这个:
def forward_slash_to_back(string)
...
def back_slash_to_forward(string)
...
def add_back_slash_for_post(string)
...
...
case conversion_type
when /bf/i then proc=&back_slash_to_forward
when /fb/i then proc=&forward_slash_to_back
when /ad/i then proc=&add_back_slash_for_post
else proc=&add_back_slash_for_post
end
n_data=proc.call(c_data)
Run Code Online (Sandbox Code Playgroud)
但它给了我一个错误.我不知道如何在Ruby中做到这一点,任何人都可以提供帮助?非常感谢!