C++ “不能重载仅按返回类型区分的函数”是什么意思?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28420921/
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-28 20:59:12  来源:igfitidea点击:

What does "Cannot overload functions distinguished by return type alone" mean?

c++

提问by dominique120

I have this code:

我有这个代码:

In the header:

在标题中:

...
int32_t round(float v);
...

and in the source

并在来源

...
int32_t round(float v)
{
    int32_t t = (int32_t)std::floor(v);
    if((v - t) > 0.5)
        return t + 1;

    return t;
}
...

I've looked around here on this site but the examples seem a bit too complicated to me.

我在这个网站上环顾四周,但这些例子对我来说似乎有点太复杂了。

I'm learning C++ so if someone could explain to me what the error means and why it's occurring I would be grateful.

我正在学习 C++,所以如果有人能向我解释错误的含义以及它为什么会发生,我将不胜感激。

回答by Hyman

Function overloadingmeans to have multiple methods with the same name.

函数重载意味着具有多个同名的方法。

Now, the compiler, to resolve the correct overloaded method, looks at method name and arguments but NO at the return value. This means that if you have

现在,为了解析正确的重载方法,编译器会查看方法名称和参数,但不会查看返回值。这意味着如果你有

int round(float something) { ... }
float round(float something) { ... }

Then the compiler is not able to distinguish them and know which one you want to invoke at a call point. So in your case this means that there is already another roundmethod which accepts a float.

然后编译器无法区分它们并知道您要在调用点调用哪一个。所以在你的情况下,这意味着已经有另一种round方法接受 a float