C代表输入更改功能的行为
我在C中的程序具有一定的功能(#明显)。该程序从用户获取输入,然后该用户可以选择不同的实现,例如myProgram -v1或myProgram -v2 ...
-v1,-v2的此规范,...决定该函数如何执行特定的计算。
例如。
for (int i = 0; i < len; i++) {
i += myFunctionWhichChangesBehaviorOnUserInput(arr[i]);
}
现在,我不想为每个V创建一个单独的函数,然后更改各自的myfunction bebehangesbehavioronuserinput()函数。
我知道您可以在Java中这样做。
interface Compute {
double compute(double n);
}
... some imple of Compute
class Task {
Compute compute;
void setCompute(Compute c) {this.compute = c}
double doMyStuff(double[] arr) {
double n = 0;
for (int i = 0; i < arr.length; i++) {
n += compute.compute(arr[i]);
}
return n;
}
}
您如何在C中实现此目标,必须以某种方式实现。
my program in C has some functionality (#obviously). The program gets input from the user, this user can then choose different implementations, e.g. myProgram -V1, or myProgram -V2 ...
This specification of -V1, -V2, ... decides how the function performs a particular calculation.
E.g..
for (int i = 0; i < len; i++) {
i += myFunctionWhichChangesBehaviorOnUserInput(arr[i]);
}
Now I don't want to create a separate function for each V and then change the respective myFunctionWhichChangesBehaviorOnUserInput() function there.
I know you can do it this way in java.
interface Compute {
double compute(double n);
}
... some imple of Compute
class Task {
Compute compute;
void setCompute(Compute c) {this.compute = c}
double doMyStuff(double[] arr) {
double n = 0;
for (int i = 0; i < arr.length; i++) {
n += compute.compute(arr[i]);
}
return n;
}
}
How can you implement this in C, must be possible somehow.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
可以通过:
我们可以创建一个包含有效命令行字符串的结构,以及指向相应功能的指针:
然后声明此类结构的数组:
完整示例:
注意:此代码稀疏使用错误处理。考虑添加界限检查,ARGV消毒和类似。
It can be done by:
We can create a struct containing a valid command line string as well as a pointer to the corresponding function:
Then declare an array of such structs:
Full example:
Note: This code is sparse with error handling. Consider adding bounds checks, argv sanitizing and similar.
听起来您想要功能指针。
您可以设置功能指针,然后调用指针指向的功能。这类似于您的Java代码。
It sounds like you want function pointers.
You can set the function pointer, and then call the function pointed to by the pointer. This is analogous to your Java code.