调用参数少于所需的函数

时间:2014-12-30 10:01:02

标签: c++ function parameters optional-parameters

我想在另一个函数 XYZ 中调用函数 ABC ,但除了 s 之外,其他函数的参数不可用。我甚至都不需要它们。我的目的只能通过 s 来解决。但是因为我已经使用参数 s t u 声明了这个函数。我需要声明这样,因为函数 ABC 需要它们。

现在如何解决这个问题。

bool ABC (int s, float t, int u)
{
     Function Implementation;
}

void XYZ (float a)
{
    Statement 1;
    Statement 2;

    if(ABC(s, t, u))
       Statement 3;

}

void main()
{
 Have parameters s, t, u and a with me.

//Call Function
  XYZ(a);

}

1 个答案:

答案 0 :(得分:1)

您已拥有bool ABC (int s, float t, int u)功能。如果您只使用一个参数(在您的情况下为 s )声明另一个名为 ABC 的函数,那么您可以使用任何具有相同名称的函数:

bool ABC (typename s)  //the return type can be anyithing, not necessarily bool
{
     Another Function Implementation;
}

现在您可以将ABC功能与一个参数一起使用,而另一个版本具有3个具有相同功能名称的参数。这就是函数重载意味着什么。

if(ABC(s)) //ABC(s,t,u) would be working too
       Statement;

请注意,C ++语言为您提供了第二种处理可选参数的方法。通过使用特定值初始化最后n个参数,您将能够保留其中一些参数。在这种情况下,在函数的实现中,左参数将被赋予初始值:

bool ABC (int s, float t=0, int u=0)
{
     Function Implementation;
}

int main()
{
  //ABC() won`t work
  ABC(2) //s=2; t=0; u=0;
  ABC(2,3) //s=2; t=3; u=0;
  ABC(2,3,4) //s=2; t=3; u=4 
}

请注意,因为您不能通过使用两个参数调用函数来仅设置 s u 。函数声明中的参数顺序很重要。

此外,在声明中为参数分配函数不应以正常方式获取的值(这些值可以是0,INT_MIN (intiger值的最小值 - 在<climits>中定义)或其他任何依赖于你的问题)你可以在你的实现中轻松检查用于调用函数的参数数量:

#include <climits>
#include <cfloats>

bool ABC (int s, float t=FLT_MAX, int u=INT_MAX)
{
   if(u == INT_MAX){...} //this means that you don`t set u

   if(t == FLT_MAX){...} //this means you set only s
}
相关问题