What does '&' mean in C++?

后端 未结 11 1679
隐瞒了意图╮
隐瞒了意图╮ 2021-01-18 02:20

What does \'&\' mean in C++?

As within the function

void Read_wav::read_wav(const string &filename)
{

}

And what is its equiv

11条回答
  •  轮回少年
    2021-01-18 03:05

    In that context, the & makes the variable a reference.

    Usually, when you pass an variable to a function, the variable is copied and the function works on the copy. When the function returns, your original variable is unchanged. When you pass a reference, no copy is made and changes made by the function show up even after the function returns.

    C doesn't have references, but a C++ reference is functionally the same as a pointer in C. Really the only difference is that pointers have to be dereferenced when you use them:

        *filename = "file.wav";
    

    But references can be used as though they were the original variable:

        filename = "file.wav";
    

    Ostensibly, references are supposed to never be null, although it's not impossible for that to happen.

    The equivalent C function would be:

         void read_wav(const char* filename)
         {
    
         }
    

    This is because C doesn't have string. Usual practice in C is to send a pointer to an array of characters when you need a string. As in C++, if you type a string constant

        read_wav("file.wav");
    

    The type is const char*.

提交回复
热议问题