C++ 对函数的引用不明确

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15037705/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 18:55:02  来源:igfitidea点击:

Reference to function is ambiguous

c++functionoverloading

提问by MarJamRob

Why is this cause a compiler error, stating that my references are ambiguous? I have a float, intand string, which should all create separate function signatures, right?

为什么这会导致编译器错误,指出我的引用不明确?我有一个float, intand string,它们都应该创建单独的函数签名,对吗?

Here is what I have so far:

这是我到目前为止所拥有的:

#include <iostream>
#include <string>
using namespace std;

int plus(int a, int b);
float plus(float a, float b);
string plus(string a, string b);

int main(void)
{
    int n = plus(3, 4);
    double d = plus(3.2, 4.2);
    string s = plus("he", "llo");
    string s1 = "aaa";
    string s2 = "bbb";
    string s3 = plus(s1, s2);
}

int plus(int a, int b) {
    return a+b;
} // int version

float plus(float a, float b) {
    return a+b;
} // float version

string plus(string a, string b) {
    return a+b;
} // string version

回答by John Calsbeek

First, don't use using namespace std;. In this case, there happens to be a struct called std::plus—oh, wait, never mind, that's actually called plusand its constructor is thrown into the bucket for overload resolution with your function called plus.

首先,不要使用using namespace std;. 在这种情况下,恰好有一个结构称为 -std::plus哦,等等,别介意,它实际上被调用了,plus并且它的构造函数被扔进了存储桶中,用你的函数调用了重载解析plus



Second, you have an ambiguity because 3.2and 4.2are of type doubleand can convert equally well to floator int.

其次,您有歧义,因为3.2and4.2是类型double并且可以同样好地转换为floator int

This is a simplification, but when it comes to passing numbers to an overloaded function, C++ basically uses these rules:

这是一种简化,但在将数字传递给重载函数时,C++ 基本上使用以下规则:

  1. If all the arguments exactly match one of the overloads, then use that one.
  2. If all the arguments can be promoted to match one of the overloads, then use that one.
  3. If all the arguments can be numerically converted to match one of the overloads, then use that one.
  1. 如果所有参数与重载之一完全匹配,则使用该重载。
  2. 如果可以提升所有参数以匹配重载之一,则使用该重载。
  3. 如果所有参数都可以进行数字转换以匹配重载之一,则使用该重载。

If you have multiple candidates at a specific level, then that is an ambiguity. Crucially, a doubledoes not promote to a float—that would be a downgrade. So it has to use a standard conversion to a float, which ties with the standard conversion to an int, so those two overloads are ambiguous.

如果您在特定级别有多个候选人,那么这是一个歧义。至关重要的是,adouble不会升级为floata——那将是降级。所以它必须使用到 a 的标准转换float,这与到 an 的标准转换有联系int,所以这两个重载是不明确的。

回答by user1610015

Call the float overload like this:

像这样调用浮点重载:

double d = plus(3.2f, 4.2f);

A constant like 3.2 actually has type double.

像 3.2 这样的常量实际上具有double类型。