Use of the & operator in C++ function signatures

后端 未结 9 952
刺人心
刺人心 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:26

    The & character in C++ is dual purpose. It can mean (at least)

    1. Take the address of a value
    2. Declare a reference to a type

    The use you're referring to in the function signature is an instance of #2. The parameter string& str is a reference to a string instance. This is not just limited to function signatures, it can occur in method bodies as well.

    void Example() {
      string s1 = "example";
      string& s2 = s1;  // s2 is now a reference to s1
    }
    

    I would recommend checking out the C++ FAQ entry on references as it's a good introduction to them.

    • https://isocpp.org/wiki/faq/references

提交回复
热议问题