This symbol is particularly confusing, because in C ++, &
there are two different uses:
- Obtain the variable address
- Passed by reference
The first example,
int main()
{
std::string s = "Hello";
std::string*p = &s;
std::cout << p << std::endl;
std::cout << *p << std::endl;
return 0;
}
0x7ffd05129510
Hello
[Finished in 0.2s]
Example, the variable p
used *
declared as a pointer, variable s
address by &
assigning to the symbol p
.
int main()
{
std::string s = "Hello";
std::string &r = s;
std::cout << s << std::endl;
std::cout << r << std::endl;
r = "New Hello";
std::cout << s << std::endl;
std::cout << r << std::endl;
std::cout << &s << std::endl;
std::cout << &r << std::endl;
std::cout << (&s == &r) << std::endl;
return 0;
}
Hello
Hello
New Hello
New Hello
0x7ffc844cc660
0x7ffc844cc660
1
[Finished in 0.2s]
Example, the variable r
is a variable s
of Reference ,. In the same memory space to refer to the location
&
may be used to declare a variable reference function,
void foo(std::string& str)
{
str[0] = 'a';
std::cout << str << std::endl;
}
int main()
{
std::string s = "Hello";
foo(s);
return 0;
}
In this example, the variables str
in the function foo
is a variable s
reference, and all of the str
operations equivalent to s
the operations.