为什么引用的常量性会影响是否可以使用其他类型的变量进行初始化? [英] Why does the constness of a reference affect whether it can be initialized with a variable of a different type?

查看:119
本文介绍了为什么引用的常量性会影响是否可以使用其他类型的变量进行初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这些代码无法编译?

Why does this code fail to compile?

 double d ;
 int & i1 = d // Compilation FAILS  

这是做什么的?

 double d ;
 const int & i = d // Compilation Succeeds

请,我有兴趣了解C ++设计人员的想法,即他们允许一种行为而不允许另一种行为.

Please, I am interested in knowing what was in mind of C++ designers that they allowed one behavior while disallowed another.

无论哪种情况,无论技术上是否可行,我都知道这是不道德的. 也供我参考,我在Mac上使用"-O0 -g3 -Wall -c -fmessage-length = 0"的GCC

I know in either case it's immoral, independent of technically possible or not. Also FYI I am using GCC on mac with "-O0 -g3 -Wall -c -fmessage-length=0"

推荐答案

因为它会创建一个临时的int,在其中转换双精度数,并且可变引用不能绑定到临时对象,而const临时对象可以绑定.

Because it creates a temporary int where the double is converted, and mutable references cannot bind to temporaries, whereas const ones can.

允许可变引用绑定到临时对象的问题相对很清楚.

The problem with allowing mutable references to bind to temporaries is relatively clear.

Derived* ptr;
Base*& baseptr = ptr;
baseptr = new Base;
ptr->SomeDerivedFunction();

这篇关于为什么引用的常量性会影响是否可以使用其他类型的变量进行初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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