【发布时间】: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()时离开NULLinteger或string,具体取决于您的输入类型,然后在push()您测试哪个不是NULL并为实际变量类型做必要的事情。
标签: c overloading variable-types