有没有办法在C中实现函数重载?我正在寻找简单的函数被重载像

foo (int a)  
foo (char b)  
foo (float c , int d)

我认为没有直接的方法;我在寻找变通办法,如果有的话。


当前回答

我希望下面的代码将帮助您理解函数重载

#include <stdio.h>
#include<stdarg.h>

int fun(int a, ...);
int main(int argc, char *argv[]){
   fun(1,10);
   fun(2,"cquestionbank");
   return 0;
}
int fun(int a, ...){
  va_list vl;
  va_start(vl,a);

  if(a==1)
      printf("%d",va_arg(vl,int));
   else
      printf("\n%s",va_arg(vl,char *));
}

其他回答

有以下几种可能性:

Printf样式函数(类型作为参数) Opengl风格函数(输入函数名) c++的c子集(如果你能使用c++编译器)

你不能只使用c++而不使用除这个以外的所有其他c++特性吗?

如果仍然没有严格的C,那么我会推荐变进函数代替。

就你的意思来说——不,你不能。

你可以像这样声明一个va_arg函数

Void my_func(char*格式,…);

,但是您需要在第一个参数中传递一些关于变量数量及其类型的信息-就像printf()所做的那样。

我希望下面的代码将帮助您理解函数重载

#include <stdio.h>
#include<stdarg.h>

int fun(int a, ...);
int main(int argc, char *argv[]){
   fun(1,10);
   fun(2,"cquestionbank");
   return 0;
}
int fun(int a, ...){
  va_list vl;
  va_start(vl,a);

  if(a==1)
      printf("%d",va_arg(vl,int));
   else
      printf("\n%s",va_arg(vl,char *));
}

这可能没有任何帮助,但如果你使用clang,你可以使用overloadable属性-即使在编译为C时也可以

http://clang.llvm.org/docs/AttributeReference.html#overloadable

extern void DecodeImageNow(CGImageRef image, CGContextRef usingContext) __attribute__((overloadable));
extern void DecodeImageNow(CGImageRef image) __attribute__((overloadable));

实现

void __attribute__((overloadable)) DecodeImageNow(CGImageRef image, CGContextRef usingContext { ... }
void __attribute__((overloadable)) DecodeImageNow(CGImageRef image) { ... }