当出现不明确的默认参数时,C ++编译器做什么? [英] What does the C++ compiler do when coming ambiguous default parameters?

查看:121
本文介绍了当出现不明确的默认参数时,C ++编译器做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++编译器在提供不明确的默认参数时会做什么?例如,假设有一个函数如:

What does the C++ compiler do when coming ambiguous default parameters? For example, let's say there was a function such as:

void function(int a = 0, float b = 3.1);
void function(int a, float b =1.1, int c = 0);

上述内容是否含糊不清?如果没有,当调用 function1(10)

Is the above considered ambiguous? If not, what does the compiler do (how is the function matched exactly) when calling something like function1(10) ?

谢谢!

推荐答案

以下是好的

void function(int a = 0, float b = 3.1);
void function(int a, float b =1.1, int c = 0);

以下是很好的

function(); // calls first function

但下面是不明确的

function(1); // second and first match equally well

对于重载解析(告诉要调用什么函数的过程) ,没有传递显式参数并且使用默认参数的参数将被忽略。所以编译器真的看到两个函数都有一个int参数为上述调用,不能决定。

For overload resolution (the process that tells what function to call), parameters that have not passed explicit arguments and that make use of default arguments are ignored. So the compiler really sees two functions both having one int parameter for the above call and can't decide.

以下是不成立的

void function(int a = 0, float b = 3.1);
void function(int a, float b =1.1);

对于问题中的代码,您声明了两个函数声明具有不同数量的参数),在本示例中,您只声明了一个函数。但是它的第二个声明重复了一个参数的默认参数(甚至有一个不同的值,但是这不重要)。这是不允许的。注意下面是很好的:

While for the code in your question you declare two functions (because both declarations have different number of parameters), in this example you only declare one function. But the second declaration of it repeats a default argument for a parameter (and even with a different value, but that doesn't matter anymore). This is not allowed. Note that the following is fine

void function(int a, float b = 3.1);
void function(int a = 0, float b);

合并同一函数在同一作用域中出现的声明的默认参数集合,仅适用于出现在相同范围内的内容。所以下面是有效的

The set of default arguments for declarations that appear in the same scope for the same function are merged, and only for those that appear in the same scope. So the following is valid

void function(int a = 0, float b = 3.1);
void function1() {
  void function(int a, float b = 1.1); 
  function(0);
}

这会调用 1.1 传递给 b

这篇关于当出现不明确的默认参数时,C ++编译器做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆