什么是C ++中的隐式解引用 [英] What is implicit dereference in C++

查看:167
本文介绍了什么是C ++中的隐式解引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++中的隐式解引用到底是什么意思?是否意味着当我把一个变量的引用传递给一个函数参数我不需要&在前面使用它的值?

What exactly does implicit dereference in C++ mean? Does it mean when I pass a reference to variable into a function parameter I don't need the & in front of it to use its value?

推荐答案

我假设你的教学试图解释指针和引用之间的区别。

I assume that you teaching was trying to explain the difference between pointers and references.

将引用指向隐式取消引用的指令是相对常见的(但在技术上并不准确)。

It is relatively common (though not technically accurate) to refer to references as fancy pointers that do implicit de-referencing.

int   x    = 5;
int*  xP   = &x;
int&  xR   = x;


xR  = 6; // If you think of a reference as a fancy pointer
         // then here there is an implicit de-reference of the pointer to get a value.

*xP = 7; // Pointers need an explicit de-reference.

正确的方式是是一个花哨指针。你需要以自己的术语思考引用。它们基本上是现有变量的另一个名称(AKA别名)。

The correct way to think about is not to use the "A reference is a fancy pointer". You need to think about references in their own terms. They are basically another name for an existing variable (AKA an alias).

所以当你通过引用一个函数传递一个变量时。这意味着该函数使用通过其别名传递的变量。该函数具有现有变量的另一个名称。当函数修改变量时,它会修改原始值,因为引用原始变量(只是其另一个名称)。

So when you pass a variable by reference to a function. This means the function is using the variable you passed via its alias. The function has another name for an existing variable. When the function modifies the variable it modifies the original because the reference is the original variable (just another name for it).

你问:


我不需要&在其前面使用其值?

I don't need the & in front of it to use its value?

不需要添加&。

No you don't need to add the &.

int f(int& x)  // pass a value by reference
{
    x =5;
}

int plop = 8;
f(plop);
// plop is now 5.

这篇关于什么是C ++中的隐式解引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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