What does \'&\' mean in C++?
As within the function
void Read_wav::read_wav(const string &filename)
{
}
And what is its equiv
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*
.
The ampersand is used in two different meanings in C++: obtaining an address of something (e.g. of a variable or a function) and specifying a variable or function parameter to be a reference to an entity defined somewhere else. In your example, the latter meaning is in use.
C does not have strictly speaking anything like the reference but pointers (or pointers to pointers) have been user for ages for similar things.
See e.g. http://www.cprogramming.com/tutorial/references.html, What are the differences between a pointer variable and a reference variable in C++? or http://en.wikipedia.org/wiki/Reference_%28C%2B%2B%29 for more information about references in C++.
In this particular case, std::string has a c_str method which returns a const char *. You can make a parallel C version and then have your C++ do something like:
void Read_wav::read_wav(const string &filename)
{
do_read_wav(internal_read_wav, filename.c_str());
}
where do_read_wav is your C routine and internal_read_wav is a pointer to a C-style struct.
void do_read_wav(struct Read_wav rw, const char * filename)
Now, if you are storing information in the class, you need to make a C struct [all of the fields must be POD, etc]
In C, you would write it this way:
void read_wav(struct Read_wav* , const char * pSzFileName)
{
}
std::string is the C++ way of dealing with array of const char.
& is a C++ reference. It behaves just as if you were handling the pointer behind ( its is mainly a syntactic sugar, thought it prompts the contract that the pointer behind should not be null).
&filename means this is a reference to filename.