简体   繁体   English

如果其中一个具有引用,如何定义两个具有相同名称和参数的函数?

[英]How to define two functions with the same name and parameters, if one of them has a reference?

I have code: 我有代码:

int SomeClass::sum(int x)
{
    return x+=x;
}

int SomeClass::sum(int & x)
{
    return x+=x;
}

.... ....

int num = 0;
int result = sum(num);

that not work. 那行不通。 How I can use both functions and indicate which of them I want to use when I сall them? 我如何使用这两种功能,并在全部使用它们时指出要使用的功能?

You can provide two different overloads taking int& and const int& , which might somehow meet your needs... 您可以提供int&const int&两个不同的重载,这可能会以某种方式满足您的需求...

But the whole code is a bit strange... in the function that takes the argument by value you are modifying it ( += ), when it probably makes sense to only read it return x+x; 但是整个代码有点奇怪...在按值获取参数的函数中,您正在修改它( += ),而只读取它可能有意义,则return x+x; . In the overload that takes the reference, you are both modifying the argument and returning the new value. 在采用引用的重载中,您将同时修改参数并返回新值。 That is a bit strange. 有点奇怪。

Other than that, sum is a horrible name for a function that multiplies by 2. 除此之外, sum是乘以2的函数的可怕名称。

You can not have such functions in C++ . C++不能有这样的功能。 They will have to be named differently for instance sumByCopy and sumByRef . 必须为实例sumByCopysumByRef命名不同的sumByRef How would you expect the compiler to decide which one are you referring to at each point? 您如何期望编译器在每个点上决定要引用哪个?

You can overload in this way, it will compile OK if you do not call any of them directly. 您可以通过这种方式重载,如果您不直接调用它们中的任何一个,它将编译OK。 However, it will cause ambiguity when you call sum(num) . 但是,当您调用sum(num)时,它将引起歧义。 Therefore, it is no sense to provide those overloads of a function since we cannot directly call none of them. 因此,提供这些函数的重载是没有意义的,因为我们不能直接调用它们。 This kind of overloads is useless and violates good practice. 这种重载是没有用的,并且违反了良好实践。

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

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