通过参考“高级”概念? [英] Passing by reference "advanced" concept?

查看:130
本文介绍了通过参考“高级”概念?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当你这样做:

int square(int& x) { return x*x;};

int s = square(40); // This gives error

要解决此问题,请执行以下操作:

To fix this you do this:

int square(const int& x) { return x*x;};

int s = square(40); // This is OK



我理解40是一个常数,所以如果我这样做: / p>

I understand that 40 is a constant but so what if I do this:

const int& x = 40 


$ c>关键字?这是编译器保护的方式,没有人可以更改 x 引用的值?

40是一个常量,所以我们甚至不知道它在内存中的位置,但编译器不知道这个地址,因此将值从40改为30示例应该被允许,因为编译器可以只到地址& 40 并将值更改为30?

40 is a const so we don't even know its location in memory, but shouldn't the compiler know this address, therefore changing the value from 40 to 30 for example should be allowed since the compiler can just go to address &40 and change the value to 30?

推荐答案

你混淆常量和字面量。它们是类似的,但不是等价的。 40 不是一个常数,它是一个字面值。

You're confusing constants and literals. They are similar, but not equivalent. 40 is not a constant, it's a literal.

不能通过引用传递一个文字,因为if你通过引用传递一些东西,这意味着它可以被修改 - 文字不能。考虑以下内容:

You can't pass a literal by reference, since if you pass something by reference, it means it can be modified - literals cannot. Consider the following:

void foo(int &i)
{
    i = 1;
}

foo(0); // What on Earth? 0 == 1?

但是,如果你传递一个对常量的引用,即使它是一个引用,函数也不允许修改它的参数(因为它是一个常量),所以现在你可以安全地传递一个字面量 - 现在有意义,因为没有可能该函数修改其参数。

If you, however, pass a reference to a constant, it means that even if it's a reference, the function is not permitted to modify its argument (since it's a constant), so now you can safely pass in a literal - it now makes sense, since there's no possibility for the function modifying its argument.

这篇关于通过参考“高级”概念?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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