使用& C++ 中的运算符函数签名

发布于 2024-11-27 09:29:51 字数 416 浏览 0 评论 0原文

我目前正在阅读 Accelerated C++,我意识到我不太明白如何 &适用于函数签名。

int* ptr=#

意味着 ptr 现在保存了 num 的地址,但这意味着什么呢?

void DoSomething(string& str)

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

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

它时,它创建的是 str.我认为它会引发错误,因为我试图将指针分配给变量。

这里发生了什么?使用 * 和 & 的含义是什么?在函数调用中?

I'm currently reading through Accelerated C++ and I realized I don't really understand how & works in function signatures.

int* ptr=#

means that ptr now holds the address to num, but what does that mean?

void DoSomething(string& str)

from what I understand that is a pass by reference of a variable (which means passing the address) but when I do

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

what it creates is a copy of str. What I thought it would do is raise an error since I'm trying to assign a pointer to a variable.

What is happening here? And what is the meaning of using * and & in function calls?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

聽兲甴掵 2024-12-04 09:29:51

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

所以

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.

A reference is not a pointer, they're different although they serve similar purpose.
You can think of a reference as an alias to another variable, i.e. the second variable having the same address. It doesn't contain address itself, it just references the same portion of memory as the variable it's initialized from.

So

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.
儭儭莪哋寶赑 2024-12-04 09:29:51

C++ 中的 & 字符有双重用途。它可以意味着(至少)

  1. 获取值的地址
  2. 声明对类型的引用

您在函数签名中引用的用途是#2 的实例。参数string& str 是对 string 实例的引用。这不仅限于函数签名,也可能发生在方法体中。

void Example() {
  string s1 = "example";
  string& s2 = s1;  // s2 is now a reference to s1
}

我建议您查看有关参考的 C++ FAQ 条目,因为它是对它们的很好的介绍。

The & character in C++ is dual purpose. It can mean (at least)

  1. Take the address of a value
  2. Declare a reference to a type

The use you're referring to in the function signature is an instance of #2. The parameter string& str is a reference to a string instance. This is not just limited to function signatures, it can occur in method bodies as well.

void Example() {
  string s1 = "example";
  string& s2 = s1;  // s2 is now a reference to s1
}

I would recommend checking out the C++ FAQ entry on references as it's a good introduction to them.

哑剧 2024-12-04 09:29:51

在阅读 Accelerated C++ 第 10 章之前,您不应该对指针有任何了解!

引用为其他地方存在的内容创建另一个名称,即别名。就是这样。不涉及隐藏指针或地址。别往窗帘后面看!

想想一个叫罗伯特的人

guy   Robert;

有时你可能想叫他鲍勃

guy& Bob = Robert;

现在鲍勃和罗伯特指的是同一个人。你不会得到他的地址(或电话号码),只是同一件事的另一个名字。

在您的函数中,

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

它的工作原理完全相同,str 是其他地方存在的某些字符串的另一个名称。

不要关心这是如何发生的,只需将引用视为某个对象的名称即可。
编译器必须弄清楚如何连接名称,而您不必这样做。

You shouldn't know anything about pointers until you get to chapter 10 of Accelerated C++ !

A reference creates another name, an alias, for something that exists elsewhere. That's it. There are no hidden pointers or addresses involved. Don't look behind the curtain!

Think of a guy named Robert

guy   Robert;

Sometimes you may want to call him Bob

guy& Bob = Robert;

Now Bob and Robert both refer to the same guy. You don't get his address (or phone number), just another name for the same thing.

In your function

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

it works exactly the same, str is another name for some string that exists somewhere else.

Don't bother with how that happens, just think of a reference as a name for some object.
The compiler has to figure out how to connect the names, you don't have to.

饭团 2024-12-04 09:29:51

在分配变量(即 int* ptr = &value)的情况下,使用 & 符号将返回变量的地址(在本例中为 <代码>值)。

在函数参数中,使用&符号意味着您正在传递对变量内存中同一物理区域的访问或引用(如果您不使用它,则会发送一个副本)。如果您使用星号作为参数的一部分,则表明您正在传递一个变量指针,这将实现几乎相同的效果。此处的区别在于,使用 & 符号时,您可以通过名称直接访问变量,但如果传递指针,则必须遵循该指针来获取和操作实际值:

void increase1(int &value) {
   value++;
}

void increase2(int *value) {
   (*value)++;
} 

void increase3(int value) {
   value++;
}

请注意,increase3 对您传递给它的原始值没有任何作用,因为只发送了一个副本:

int main() {
   int number = 5;
   increase1(number);
   increase2(&number);
   increase3(number);
   return 0;
}

3 个函数调用结束时 number 的值是 7,而不是8.

In the case of assigning variables (ie, int* ptr = &value), using the ampersand will return the address of your variable (in this case, address of value).

In function parameters, using the ampersand means you're passing access, or reference, to the same physical area in memory of the variable (if you don't use it, a copy is sent instead). If you use an asterisk as part of the parameter, you're specifying that you're passing a variable pointer, which will achieve almost the same thing. The difference here is that with an ampersand you'll have direct access to the variable via the name, but if you pass a pointer, you'll have to deference that pointer to get and manipulate the actual value:

void increase1(int &value) {
   value++;
}

void increase2(int *value) {
   (*value)++;
} 

void increase3(int value) {
   value++;
}

Note that increase3 does nothing to the original value you pass it because only a copy is sent:

int main() {
   int number = 5;
   increase1(number);
   increase2(&number);
   increase3(number);
   return 0;
}

The value of number at the end of the 3 function calls is 7, not 8.

谁对谁错谁最难过 2024-12-04 09:29:51

它是一个引用,允许函数修改传递的字符串,这与普通字符串参数不同,普通字符串参数的修改不会影响传递给函数的字符串。

你经常会看到 const string& 类型的参数;这是出于性能目的而完成的,因为内部引用不会创建字符串的副本。

It's a reference which allows the function to modify the passed string, unlike a normal string parameter where modification would not affect the string passed to the function.

You will often see a parameter of type const string& which is done for performance purposes as a reference internally doesn't create a copy of the string.

玉环 2024-12-04 09:29:51
int* ptr=#

第一种情况:由于 ptr 是一个内存,它存储变量的地址。的&运算符返回 num 在内存中的地址。

void DoSomething(string& str)

第二种情况:& 运算符用于表明变量是通过引用传递的,并且可以由函数更改。

所以基本上 &根据上下文,运算符有 2 个功能。

int* ptr=#

1st case: Since ptr is a memory and it stores the address of a variable. The & operator returns the address of num in memory.

void DoSomething(string& str)

2nd case: The ampersand operator is used to show that the variable is being passed by reference and can be changed by the function.

So Basically the & operator has 2 functions depending on the context.

橘虞初梦 2024-12-04 09:29:51

虽然编译器可以通过将地址作为指针传递来实现按引用传递,但从语义上讲,它与地址或指针无关。简单来说,它只是变量的别名。

C++ 有很多情况下,语法在具有不同语义的不同上下文中重用,这就是其中之一。

While pass by reference may be implemented by the compiler by passing the address as a pointer, semantically it has nothing to do with addresses or pointers. in simple terms it is merely an alias for a variable.

C++ has a lot of cases where syntax is reused in different contexts with different semantics and this is one of those cases.

又爬满兰若 2024-12-04 09:29:51

在以下情况下:

int* ptr=#

您声明一个名为 ptr 的变量,其类型为 int *(int 指针),并将其值设置为“变量 num 的地址” “(&num)。 “addressof”运算符 (&) 返回一个指针。

在以下情况下:

void DoSomething(string& str)

您将 DoSomething() 方法的第一个参数声明为“引用字符串”类型。实际上,这是定义“按引用传递”的 C++ 方式。

请注意,虽然 & 运算符在这些情况下的操作类似,但其行为方式并不相同。具体来说,当用作运算符时,您告诉编译器获取指定变量的地址;当在方法签名中使用时,您告诉编译器该参数是一个引用。还要注意,“参数作为引用”位与具有作为指针的参数不同。引用参数 (&) 会自动取消引用,并且该方法永远不会暴露底层数据的存储位置;使用指针参数,您仍然通过引用传递,但是您暴露了存储变量的方法,并且如果该方法无法执行取消引用(这种情况发生的频率比您想象的要高),则可能会暴露问题。

In the case of:

int* ptr=#

you are declaring a variable named ptr with a type of an int * (int pointer), and setting its value to the "address of the variable num" (&num). The "addressof" operator (&) returns a pointer.

In the case of:

void DoSomething(string& str)

you are declaring the first parameter of the DoSomething() method to be of type "reference to string". Effectively, this is the C++ way of defining "pass-by-reference".

Note that while the & operator operates similarly in these cases, it's not acting in the same way. Specifically, when used as an operator, you're telling the compiler to take the address of the variable specified; when used in a method signature, you're telling the compiler that the argument is a reference. And note as well, that the "argument as a reference" bit is different from having an argument that is a pointer; the reference argument (&) gets dereferenced automatically, and there's never any exposure to the method as to where the underlying data is stored; with a pointer argument, you're still passing by reference, but you're exposing to the method where the variable is stored, and potentially exposing problems if the method fails to do a dereference (which happens more often than you might think).

韵柒 2024-12-04 09:29:51

您正在从 str 中隐式复制构造 copy。是的,str 是一个引用,但这并不意味着您不能从中构造另一个对象。在 C++ 中,& 运算符意味着以下三件事之一 -

  1. 当您定义普通引用变量时,您会为一个变量创建一个别名目的。
  2. 当您在函数参数中使用它时,它是通过引用传递 - 您还创建了对象的别名,与副本相反。在这种情况下,您不会注意到任何差异,因为它基本上是您传递给它的对象。当您传递的对象包含指针等时,它确实会产生影响。
  3. &的最后一个(与您的情况大部分无关)含义是按位AND。

考虑引用的另一种方法(尽管稍微不正确)是取消引用指针的语法糖。

You're inexplicitly copy-constructing copy from str. Yes, str is a reference, but that doesn't mean you can't construct another object from it. In c++, the & operator means one of 3 things -

  1. When you're defining a normal reference variable, you create an alias for an object.
  2. When you use it in a function paramater, it is passed by reference - you are also making an alias of an object, as apposed to a copy. You don't notice any difference in this case, because it basically is the object you passed to it. It does make a difference when the objects you pass contain pointers etc.
  3. The last (and mostly irrelevent to your case) meaning of & is the bitwise AND.

Another way to think about a reference (albeit slightly incorrect) is syntactic sugar for a dereferenced pointer.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文