在C ++中将char赋值给int引用和const int引用 [英] assigning char to int reference and const int reference in C++

查看:208
本文介绍了在C ++中将char赋值给int引用和const int引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到,将一个 char 赋值给一个 const int& $ c> int& 给出编译错误。

I noticed that assigning a char to a const int& compiles, but assigning it to a int& gives a compilation error.

char c;
int& x = c;    // this fails to compile
const int& y = c;    // this is ok

我知道,这不是一个好的做法,好奇地知道它发生的原因。

I understand that it is not a good practice to do this, but I am curious to know the reason why it happens.

我已经通过寻找赋值给不同类型的引用,赋值给一个int引用和const引用和非引用-const reference,并发现了一些有用的帖子(http://stackoverflow.com/questions/4705593/int-vs-const-int,将char赋值给int变量时的奇怪行为在C和C ++中将char转换为int 引用和const引用之间的差异作为函数参数?),但是它们似乎没有解决我的问题。

I have searched for an answer by looking for "assigning to reference of different type", "assigning char to a int reference", and "difference between const reference and non-const reference", and came across a number of useful posts (http://stackoverflow.com/questions/4705593/int-vs-const-int , Weird behaviour when assigning a char to a int variable , Convert char to int in C and C++ , Difference between reference and const reference as function parameter?), but they do not seem to be addressing my question.

如果此问题已经得到解答,我们深表歉意。

My apologies if this has been already answered before.

推荐答案

int& x = c;

这里从 char code> int 正在由编译器执行。生成的临时 int 只能绑定到 const 引用。绑定到 const int& 也将延长临时结果的生命周期以匹配它绑定的引用的生命周期。

Here an implicit conversion from char to int is being performed by the compiler. The resulting temporary int can only be bound to a const reference. Binding to a const int& will also extend the lifetime of the temporary result to match that of the reference it is bound to.

这篇关于在C ++中将char赋值给int引用和const int引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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