当出现模糊的默认参数时,C++编译器会做什么?

lal*_*ser 5 c++ compiler-construction overloading default-value

当出现模糊的默认参数时,C++编译器会做什么?例如,假设有一个函数,例如:

void function(int a = 0, float b = 3.1);
void function(int a, float b =1.1, int c = 0);
Run Code Online (Sandbox Code Playgroud)

以上是否被认为含糊不清?如果没有,那么当调用类似的东西时,编译器会做什么(函数如何完全匹配)function1(10)

谢谢!

Joh*_*itb 8

以下是好的

void function(int a = 0, float b = 3.1);
void function(int a, float b =1.1, int c = 0);
Run Code Online (Sandbox Code Playgroud)

以下也很好

function(); // calls first function
Run Code Online (Sandbox Code Playgroud)

但以下是模棱两可的

function(1); // second and first match equally well
Run Code Online (Sandbox Code Playgroud)

对于重载解析(告诉要调用哪个函数的进程),将忽略未传递显式参数且使用默认参数的参数.所以编译器确实看到两个函数都有一个int参数用于上面的调用而无法决定.

以下是不正确的

void function(int a = 0, float b = 3.1);
void function(int a, float b =1.1);
Run Code Online (Sandbox Code Playgroud)

对于您的问题中的代码,您声明了两个函数(因为两个声明具有不同数量的参数),在此示例中,您只声明一个函数.但是它的第二个声明重复了一个参数的默认参数(甚至使用不同的值,但这不再重要).这是不允许的.请注意,以下情况很好

void function(int a, float b = 3.1);
void function(int a = 0, float b);
Run Code Online (Sandbox Code Playgroud)

出现在同一函数的同一作用域中的声明的默认参数集合将合并,并且仅针对出现在同一作用域中的声明.所以以下是有效的

void function(int a = 0, float b = 3.1);
void function1() {
  void function(int a, float b = 1.1); 
  function(0);
}
Run Code Online (Sandbox Code Playgroud)

这调用1.1传递的函数b.