Address-identifier in C ++ (&)

This symbol is particularly confusing, because in C ++, &there are two different uses:

  1. Obtain the variable address
  2. 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 pused *declared as a pointer, variable saddress 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 ris a variable sof 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 strin the function foois a variable sreference, and all of the stroperations equivalent to sthe operations.

Guess you like

Origin www.cnblogs.com/yaos/p/12088949.html