使用&运算符在C ++函数签名中 [英] Use of the & operator in C++ function signatures

查看:135
本文介绍了使用&运算符在C ++函数签名中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在阅读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; //这里你得到一个地址s
string& r = s; //这里,r是对s的引用

s =Hello,world; // corrected
assert(s == * p); //这应该是你熟悉的,dereferencing一个指针
assert(s == r); //这将永远是真的,他们是双胞胎,或相同的东西,而不是

string copy1 = * p; //这是使用指针复制一个
string copy = r; //这是你看到的,希望现在你能更好地理解它。


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?

解决方案

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.

这篇关于使用&运算符在C ++函数签名中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆