可以在C中模仿名称空间,如下所示:
#include <stdio.h>
#include <math.h>
struct math_namespace {
double (*sin)(double);
};
const struct math_namespace math = {sin};
int main() {
printf("%f\n", math.sin(3));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这有什么缺点,或者只是前缀更有意义的情况?这样做似乎更干净.
该方法已在实际项目中使用,例如Jacob Navia 的C Containers Library。C 不是为面向对象编程而设计的。这并不是真正有效,因为您必须(1)访问结构并(2)取消引用函数指针。如果您确实想要前缀,我认为更改标识符仍然是最好的解决方案。