【问题标题】:c is there a way to test type of variable? or overload methods?c有没有办法测试变量的类型?还是重载方法?
【发布时间】:2012-10-25 05:56:50
【问题描述】:

我需要将一个 int 或一个字符串传递给一个堆栈的推送函数。通常我只会重载该函数,并有一个接受字符串参数和一个接受 int 参数的函数,以便仅根据参数调用适当的函数。我在 cmets 中写了我通常会包含类型的点。我只是卡在那里。

void push(Stack *S, /* int or a string */ element)
{        
    /* If the stack is full, we cannot push an element into it as there is no space for it.*/        
    if(S->size == S->capacity)        
    {                
        printf("Stack is Full\n");        
    }        
    else        
    {                
        /* Push an element on the top of it and increase its size by one*/ 

        if (/* element is an int*/)
            S->elements[S->size++] = element; 
        else if (/* element is a string */)
            S->charElements[S->size++] = element;
    }        
    return;
}

【问题讨论】:

  • 您可以尝试使用三个参数,例如:push(Stack *S, int *integer, char *string) 然后在调用 push() 时离开 NULL integerstring,具体取决于您的输入类型,然后在 push() 您测试哪个不是NULL 并为实际变量类型做必要的事情。

标签: c overloading variable-types


【解决方案1】:

在这种情况下,您可以使用union,它会自动为您管理事情:

typedef union {
   int integer; 
   char* string;
} Item;

或者如果仍然需要类型检查,您可以使用带有类型的struct 和内部的union

typedef enum { INTEGER, STRING } Type;

typedef struct
{
  Type type;
  union {
  int integer;
  char *string;
  } value;
} Item;

【讨论】:

    【解决方案2】:

    如果您的编译器已经实现了 C11 的该部分,您可以使用新功能 _Generic。例如,clang 已经实现了这个功能,对于 gcc 和堂兄弟,有一些方法可以模拟该功能:P99

    它通常通过宏来工作,像这样

    #define STRING_OR_INT(X) _Generic((X), int: my_int_function, char const*: my_str_function)(X)
    

    【讨论】:

      【解决方案3】:

      c中没有函数重载。

      您可以将类型作为参数传入,使元素参数成为指针,然后将指针重新转换为适当的类型。

      【讨论】:

      • C11 具有替换函数重载的类型泛型表达式
      【解决方案4】:

      您只能使用以该语言提供的功能。我不认为有办法在 C 中检查变量是字符串还是 int。此外,元素不能同时保存字符串和 int 在这里要小心。所以去功能重载。祝你好运

      【讨论】:

        【解决方案5】:

        你可以这样试试

        void push (Stack *S,void *element)
            {
             (*element) //access using dereferencing of pointer by converting it to int
             element // incase of char array
            }
        
            //from calling enviroment
            int i =10;
            char *str="hello world"
            push(S,&i) //in case of int pass address of int
            push(S,str) // in case of char array
        

        【讨论】:

        • 对,转成int类型
        猜你喜欢
        • 2011-04-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-12
        相关资源
        最近更新 更多