如何在C ++中实现引用? [英] How is reference implemented in C++?

查看:61
本文介绍了如何在C ++中实现引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,


int i = 5;

int& r = i;


我和r有两个不同的变量吗?

或者我和r是否占用相同的内存空间?这意味着它们是

相同的变量?


谢谢。

解决方案
<菊****** @ gmail.com>在消息中写道

news:11 ********************** @ u72g2000cwu.googlegr oups.com

例如,

int i = 5;
int& r = i;

我和r是两个不同的变量吗?
或者做我和r占用相同的内存空间?这意味着它们是相同的变量吗?

谢谢。




C ++标准没有说明如何实现引用。但是,它们通常用const指针实现
。因此


int& r = i;


可以,在幕后,类似


int * const ptr =& i;


及以后


r = 9;


可能相当于


* ptr = 9;


-

John Carson




< ju ****** @ gmail.com>在消息中写道

news:11 ********************** @ u72g2000cwu.googlegr oups.com ...


Re:如何在C ++中实现引用?


语言标准不需要任何

特定机制。每个实现

都可以任意方式执行,只要

行为符合。

例如,

int i = 5;
int& r = i;

我和r是两个不同的变量吗?


编号参考不是一个对象,只是一个

替代名称(''alias'')。

或者我和r占用相同的存储空间?


NO。 ''我'占据了存储空间。 ''r'可能会也可能不会。

但是没关系。

这意味着它们是相同的变量吗?




名称我和r指的是同一个存储空间。

''r''不是一个对象,但指的是一个。


-Mike


它就像一个带有2个名字的变量......

使用相同的内存位置...据我所知这是


For example,

int i = 5;
int &r = i;

Are i and r two different variables?
Or do i and r occupy the same memory space? that means they are the
same variable?

Thanks.

解决方案

<ju******@gmail.com> wrote in message
news:11**********************@u72g2000cwu.googlegr oups.com

For example,

int i = 5;
int &r = i;

Are i and r two different variables?
Or do i and r occupy the same memory space? that means they are the
same variable?

Thanks.



The C++ standard doesn''t say how references are implemented. However, they
are often implemented in terms of const pointers. Thus

int & r = i;

may, "behind the scenes", be something like

int * const ptr = &i;

and a later

r = 9;

may be the equivalent of

*ptr = 9;

--
John Carson



<ju******@gmail.com> wrote in message
news:11**********************@u72g2000cwu.googlegr oups.com...

Re: How is reference implemented in C++?

THe language standard does not require any
particular mechanism. Each implementation
is free to do it in any way, as long as
the behavior is compliant.

For example,

int i = 5;
int &r = i;

Are i and r two different variables?
No. A reference is not an object, merely an
alternate name (''alias'') for one.
Or do i and r occupy the same memory space?
NO. ''i'' occupies storage. ''r'' might or might not.
But it shouldn''t matter.
that means they are the
same variable?



The names ''i'' and ''r'' refer to the same storage.
''r'' isn''t an object, but refers to one.

-Mike


its like one variable with 2 names...
the same memory location is used...this is to the best of my knowledge


这篇关于如何在C ++中实现引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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