简体   繁体   English

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

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

I have this code:我有这段代码:

In the header:在 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++,所以如果有人可以向我解释错误的含义以及发生错误的原因,我将不胜感激。

Function overloading means 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. 现在,编译器解析正确的重载方法,查看方法名称和参数,但返回值为NO。 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 round method which accepts a float . 所以在你的情况下,这意味着已经有另一个接受float round方法。

#include <iostream>
using namespace std;
class complex
{
private:
    int real;
    int img;

public:
    void set(int r, int i)
    {
        real = r;
        img = i;
    }
    complex(int r = 0, int i = 0)
    {
        real = r;
        img = i;
    }
    int getReal(){
        return real ;
    }
    int getImg(){
        return img ;
    }
    friend complex operator+(complex x, complex y);
    friend void Display(complex y);
    
};
/*freind functions of complex*/
complex operator+(complex x, complex y)
{
    complex z;
    z.real = x.getReal() + y.getReal();
    z.img = x.getImg() + y.getImg();
    return z;
}
void Display(complex y)
{

    cout << y.getReal()<< "+i" << y.getImg() << endl;
    return 0;
}
int main()
{
    complex c1, c2, c3;
    c1.set(78, 9);
    c2.set(68, 9);
    c3 = c1 + c2;
    c1.Display(c3);

    return 0;
}

C++ standard doesn't support overloading based on return type alone, it's because the return type doesn't play a role in determining the function being called. C++ 标准不支持单独基于返回类型的重载,这是因为返回类型在确定被调用的 function 中不起作用。 The return type is only determined at runtime, and thus it's not part of the function signature which is used by the compiler to decide which function to call.返回类型仅在运行时确定,因此它不是编译器用来决定调用哪个 function 的 function 签名的一部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM