In C++, what does & mean after a function's return type?

后端 未结 11 1344
情歌与酒
情歌与酒 2020-11-29 23:49

In a C++ function like this:

int& getNumber();

what does the & mean? Is it different from:

int getNumb         


        
相关标签:
11条回答
  • 2020-11-30 00:24

    The difference is that without the & what you get back is a copy of the returned int, suitable for passing into other routines, comparing to stuff, or copying into your own variable.

    With the &, what you get back is essentially the variable containing the returned integer. That means you can actually put it on the left-hand side of an assignment, like so:

    getNumber() = 200;
    
    0 讨论(0)
  • 2020-11-30 00:24

    The first version allows you to write getNumber() = 42, which is probably not what you want. Returning references is very useful when overloading operator[] for your own containers types. It enables you to write container[9] = 42.

    0 讨论(0)
  • 2020-11-30 00:27

    It's a reference

    0 讨论(0)
  • 2020-11-30 00:32

    It means it's returning a reference to an int, not an int itself.

    0 讨论(0)
  • 2020-11-30 00:34

    int& getNumber(): function returns an integer by reference.

    int getNumber(): function returns an integer by value.

    They differ in some ways and one of the interesting differences being that the 1st type can be used on the left side of assignment which is not possible with the 2nd type.

    Example:

    int global = 1;
    
    int& getNumber() {
            return global; // return global by reference.
    }
    
    int main() {
    
            cout<<"before "<<global<<endl;
            getNumber() = 2; // assign 2 to the return value which is reference.
            cout<<"after "<<global<<endl;
    
            return 0;
    }
    

    Ouptput:

    before 1
    after 2
    
    0 讨论(0)
提交回复
热议问题