What does it mean to pass a &variable to a function? E.g., string& insert ( size_t pos1, const string& str );
I understand passing a pointer, and returning a pointer:
char * strcat ( char * destination, const char * source );
You're passing a variable that contains the address to a char; returning the same.
But what does i开发者_如何学Ct mean to pass something using the reference operator? Or to return it?
string& insert ( size_t pos1, const string& str );
I mean, I understand what actually happens, I just don't understand the notation. Why isn't the notation this instead:
string * insert ( size_t pos1, const string * str ); //made up
I presume it has something to do with passing/returning the instance of a class, but what? Is this syntax valid; if not why not and if so what does it mean?
char & strcat ( char & destination, const char & source ); //made up
(all of the function declarations, except the last made-up two, are from http://www.cplusplus.com )
Simply said, a reference is a pointer without telling you it's a pointer.
If you would write the following in plain C:
void getpi (float *f)
{
*f = 3.14;
}
float v;
getpi(&v);
You can write the following in C++ using references:
void getpi (float &f)
{
f = 3.14;
}
float v;
getpi(v);
It has the additional advantage that you can move from normal by-value argument to by-reference argument, without making changes to the caller. Suppose you have this:
class X; // A rather small class that can be easily copied
void doSomething (X x);
But after a while, class X becomes really big and you don't want to pass it by value anymore. In plain C you have to change the argument to a pointer argument, and change all the callers. In C++ you can simply do this:
void doSomething (X &x);
And you don't have to change any of the callers.
Here is a useful article about when to use references instead of pointers (or const pointers): http://www.embedded.com/story/OEG20010311S0024
Using a reference instead of a const pointer achieves some of the same things, but also guarantees that the object is valid since references can be assigned arbitrary "values".
This is called a reference. Pointers are objects that point to other objects. References, on the other hand, are simply a way of referring to an existing object. References are a central feature of C++. The C++ faq has a lot more information: https://isocpp.org/wiki/faq/references
精彩评论