What does '&' mean in C++?

后端 未结 11 1601
隐瞒了意图╮
隐瞒了意图╮ 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 02:51

    & means that variable is passed via reference. So, inside your function you will have not a local copy of variable, but the original variable itself. All the changes to the variable inside the function will influence the original passed variable.

    0 讨论(0)
  • 2021-01-18 02:52

    It means that the variable is a reference. There is no direct equivalent in C. You can think of it as a pointer that is automatically dereferenced when used, and can never be NULL, maybe.

    The typical way to represent a string in C is by a char pointer, so the function would likely look like this:

    void read_wav(struct Read_wav* instance, const char *filename)
    {
    }
    

    Note: the first argument here simulates the implicit this object reference you would have in C++, since this looks like a member method.

    0 讨论(0)
  • 2021-01-18 02:52

    References are aliases, they are very similar to pointers.

    std::string is an array of char with an explicit length (that is, there can be null characters embedded within).

    There is a C-library to emulate std::string (that is, provide an encapsulated interface) called bstring for Better String Library. It relieves you from the tedium of having to deal with two distinct variables (array and length).

    You cannot use classes in C, but you can emulate them with forwarded struct (to impose encapsulation) and class methods simply become regular functions with an explicit parameter.

    Altogether, this leads to the following transformation:

    void Read_wav::read_wav(const string &filename);
    
    void read_wav(struct Read_wav* this, struct bstring const* filename);
    

    Which (apart from the struct noise) is very similar to what you had before :)

    0 讨论(0)
  • 2021-01-18 02:53

    You might want to check out Binky Pointer fun, it's a video that illustrates what Pointers and References are.

    0 讨论(0)
  • 2021-01-18 02:59

    In this case, string &filename means the function will receive a reference (a memory address) as a parameter, instead of receiving it as a copy.

    The advantage of this method is that your function will not allocate more space on the stack to save the data contained in filename.

    0 讨论(0)
  • 2021-01-18 02:59

    It's a reference, as others have said. In C, you'd probably write the function as something like

    void read_wav(struct Read_wav* rw, const char* filename)
    {
    
    }
    
    0 讨论(0)
提交回复
热议问题