常量引用的文字初始化 [英] Literal initialization for const references

查看:115
本文介绍了常量引用的文字初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码在C ++中如何工作?是逻辑的吗?

How does the following code work in C++? Is it logical?

const int &ref = 9;
const int &another_ref = ref + 6;

为什么当非const引用不允许时,C ++允许const引用的文本初始化?例如:

Why does C++ allow literal initialization for const references when the same is not permitted for non-const references? E.g.:

const int days_of_week = 7;
int &dof = days_of_week; //error: non const reference to a const object

这可以解释为,非const引用可以用来改变它所引用的变量的值。因此,C ++不允许对const变量的非const引用。

This can be explained by the fact that, a non-const reference can be used to change the value of the variable it is referring to. Hence, C++ does not permit a non-const reference to a const variable.

这可能是一个可能的解释吗? C ++不允许:

Could this be a possible explanation? C++ does not allow:

int &ref = 7;

因为这不符合逻辑,而是:

Because that is not logical, but:

const int &ref = 7;

几乎等同于:

const int val = 7;

因此,const变量允许文字初始化。

So literal initialization is permitted for const variables.

PS:我正在研究Lippman的C ++ Primer。

P.S.: I'm currently studying Lippman's C++ Primer.

推荐答案

所以你可以这样编写代码:

So you can write code like this:

void f( const string & s ) {
}

f( "foobar" );

虽然严格来说,这里实际发生的并不是字面量绑定到一个const引用 - 创建临时字符串对象:

Although strictly speaking what is actually happening here is not the literal being bound to a const reference - instead a temprary string object is created:

string( "foobar" );

,这个无名字符串绑定到引用。

and this nameless string is bound to the reference.

注意,创建非参数引用变量实际上是非常不寻常的 - 引用的主要目的是作为函数参数和返回值。

Note that it is actually quite unusual to create non-parameter reference variables as you are doing - the main purpose of references is to serve as function parameters and return values.

这篇关于常量引用的文字初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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