c++ - 在 C++ 函数签名中使用 & 运算符

标签 c++ pass-by-reference

我目前正在阅读 Accelerated C++,但我意识到我并不真正了解函数签名中的 & 工作原理。

int* ptr=#

表示 ptr 现在将地址保存到 num,但这是什么意思?

void DoSomething(string& str)

据我了解,这是通过引用传递变量(这意味着传递地址)但是当我这样做时

void DoSomething(string& str)
{
  string copy=str;
}

它创建的是 str 的拷贝。我认为它会引发错误,因为我正在尝试将指针分配给变量。

这里发生了什么?在函数调用中使用 * 和 & 是什么意思?

最佳答案

引用不是指针,尽管它们的用途相似,但它们是不同的。 您可以将引用视为另一个变量的别名,即具有相同地址的第二个变量。它本身不包含地址,它只是引用与它初始化的变量相同的内存部分。

所以

string s = "Hello, wordl";
string* p = &s; // Here you get an address of s
string& r = s; // Here, r is a reference to s    

s = "Hello, world"; // corrected
assert( s == *p ); // this should be familiar to you, dereferencing a pointer
assert( s == r ); // this will always be true, they are twins, or the same thing rather

string copy1 = *p; // this is to make a copy using a pointer
string copy = r; // this is what you saw, hope now you understand it better.

关于c++ - 在 C++ 函数签名中使用 & 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6877052/

相关文章:

java - Android NDK 中的系统调用

C++ 将 wstringstream 传递给另一个函数

c++ - 传递参数的 g++ 问题

programming-languages - 是否有一种具有 native 按引用传递/按名称传递语义的语言,可以在现代生产应用程序中使用?

javascript - 绑定(bind)函数不返回对象的引用

c++ - 如何从资源位图文件中为 directshow 滤镜加载图像数据?

c++ - 为什么非下划线名称保留给 UDL 的实现而不是相反?

c++ - 您可以在字符串文字中放置中断吗?

c++ - 难以理解 * 和 & 当它们与线程一起出现时

javascript - 拖动后的谷歌地图标记位置