简体   繁体   中英

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...

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; . 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.

You can not have such functions in C++ . They will have to be named differently for instance sumByCopy and 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. However, it will cause ambiguity when you call 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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