我目前正在阅读 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/