将&变量传递给函数是什么意思?例如,string& insert(size_t pos1,const string& str); [英] What does it mean to pass a &variable to a function? E.g., string& insert ( size_t pos1, const string& str );

查看:211
本文介绍了将&变量传递给函数是什么意思?例如,string& insert(size_t pos1,const string& str);的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我理解传递指针并返回指针:



char * strcat(char * destination,const char * source);



您正在将包含地址的变量传递给char;返回相同。



但是使用引用运算符传递东西意味着什么呢?或返回?



string& insert(size_t pos1,const string& str);



我的意思是,我明白发生了什么,我只是不明白符号。为什么不是这样的符号:



string * insert(size_t pos1,const string * str); // make up



我认为它与传递/返回类的实例有关,但是什么?此语法是否有效;



char& strcat(char& destination,const char& source); // make up



(所有的函数声明,除了最后的组成两个,都来自 http://www.cplusplus.com

解决方案

简单地说,引用是一个指针,而不告诉你它是一个指针。



如果你写下面的简单C:

  void getpi(float * f)
{
* f = 3.14;
}

float v;
getpi(& v);

您可以使用引用在C ++中编写以下内容:

  void getpi(float& f)
{
f = 3.14;
}

float v;
getpi(v);

它有额外的优点,你可以从正常的by-value参数移动到by-而不对调用者进行更改。假设你有这个:

  class X; //一个很容易复制的小类
void doSomething(X x);

但是一段时间后,类X变得很大,你不想通过它的值不再。
在纯C中,您必须将参数更改为指针参数,并更改所有调用者。
在C ++中你可以这样做:

  void doSomething(X& x); 

您不必更改任何来电者。


I understand passing a pointer, and returning a pointer:

char * strcat ( char * destination, const char * source );

You're passing a variable that contains the address to a char; returning the same.

But what does it mean to pass something using the reference operator? Or to return it?

string& insert ( size_t pos1, const string& str );

I mean, I understand what actually happens, I just don't understand the notation. Why isn't the notation this instead:

string * insert ( size_t pos1, const string * str ); //made up

I presume it has something to do with passing/returning the instance of a class, but what? Is this syntax valid; if not why not and if so what does it mean?

char & strcat ( char & destination, const char & source ); //made up

(all of the function declarations, except the last made-up two, are from http://www.cplusplus.com )

解决方案

Simply said, a reference is a pointer without telling you it's a pointer.

If you would write the following in plain C:

void getpi (float *f)
{
*f = 3.14;
}

float v;
getpi(&v);

You can write the following in C++ using references:

void getpi (float &f)
{
f = 3.14;
}

float v;
getpi(v);

It has the additional advantage that you can move from normal by-value argument to by-reference argument, without making changes to the caller. Suppose you have this:

class X;   // A rather small class that can be easily copied
void doSomething (X x);

But after a while, class X becomes really big and you don't want to pass it by value anymore. In plain C you have to change the argument to a pointer argument, and change all the callers. In C++ you can simply do this:

void doSomething (X &x);

And you don't have to change any of the callers.

这篇关于将&变量传递给函数是什么意思?例如,string& insert(size_t pos1,const string& str);的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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