Use of the & operator in C++ function signatures

后端 未结 9 969
刺人心
刺人心 2020-11-29 00:36

I\'m currently reading through Accelerated C++ and I realized I don\'t really understand how & works in function signatures.

int* ptr=#
         


        
9条回答
  •  囚心锁ツ
    2020-11-29 01:21

    You shouldn't know anything about pointers until you get to chapter 10 of Accelerated C++ !

    A reference creates another name, an alias, for something that exists elsewhere. That's it. There are no hidden pointers or addresses involved. Don't look behind the curtain!

    Think of a guy named Robert

    guy   Robert;
    

    Sometimes you may want to call him Bob

    guy& Bob = Robert;
    

    Now Bob and Robert both refer to the same guy. You don't get his address (or phone number), just another name for the same thing.

    In your function

    void DoSomething(string& str)
    {
      string copy=str;
    }
    

    it works exactly the same, str is another name for some string that exists somewhere else.

    Don't bother with how that happens, just think of a reference as a name for some object. The compiler has to figure out how to connect the names, you don't have to.

提交回复
热议问题