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

后端 未结 11 1495
情歌与酒
情歌与酒 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: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 "<

    Ouptput:

    before 1
    after 2
    

提交回复
热议问题