6

我真的可以像这样使用函数重载吗:

#include <iostream>

void foo(...)
{
   std::cout << "::foo(...) \n";
}

void foo(int)
{
   std::cout << "::foo(int) \n";
}

int main()
{
   foo(0);
   foo('A');
   foo("str");
   foo(0, 1);
}

什么标准说的?在什么情况下我会得到 ::foo(...)?

4

4 回答 4

3
void foo(int)

将接受一个类型的参数int

void foo(...)

接受任意数量的任何类型的参数。当调用没有单个int参数时,它将被选中。用处不大,一般。

另请注意,将类类型的对象传递给....

于 2012-09-15T10:34:34.230 回答
2
于 2012-09-15T10:43:39.917 回答
0

void foo(...)将采用可变参数。当参数的 no 或 type 与提供的具有相同函数名的其他函数的参数列表不匹配时,它将被调用。

foo(0);             //This will call void foo(int) function
foo('A');           //This will call void foo(int) function
foo("str");         //This will call void foo(...) function
foo(0, 1);          //This will call void foo(...) function

笔记:

尽管省略号在函数重载方面工作得很好,但强烈建议不要使用可变参数函数。至少在你有更多的 C++ 经验来理解其中的陷阱之前。我建议仅将它与 try catch 块一起使用,其中存在无法预测错误的情况。

于 2012-09-15T10:32:24.480 回答
0

当您以下列方式声明函数时:

  void foo (...) 

这意味着 foo 接受任意数量的参数。

因此,当这是必须合适的函数时,将调用此函数。

在您不写的情况下:

foo(//Some single int).

在您的特定主体中,这将发生:

foo(0)     //Calls foo(int).
foo('A)    //Calls foo (int). as you can convert a char to an int.
foo("str") //Calls foo(...) . as you can not convert a string to an int.
foo(1,2)   //Calls foo(...) . as this is the only possible function 
             cause the second foo function only takes one int.
于 2012-09-15T10:28:37.780 回答