C++中的取地址符(&)

这个符号特别容易混淆, 因为在C++中, &有两种不同用法:

  1. 获得变量地址
  2. 引用传递

第一个例子,

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]

例子中, 变量p使用*声明为指针, 将变量s的地址通过&符号赋值给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]

例子中, 变量r是变量sreference, 在内存空间中指代相同的位置.
&可以用于函数变量引用声明,

void foo(std::string& str)
{
	str[0] = 'a';
	std::cout << str << std::endl;
}
int main()
{
	std::string s = "Hello";
	foo(s);
	return 0;
}

在这个例子中, 变量str在函数foo中是变量s的 reference, 所有对str的操作, 相当于对s的操作.

原文地址:https://www.cnblogs.com/yaos/p/14014213.html