首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >是引用转换是标准转换

是引用转换是标准转换
EN

Stack Overflow用户
提问于 2017-02-23 15:08:11
回答 1查看 112关注 0票数 1

c++标准说标准转换包括

代码语言:javascript
复制
 A standard conversion sequence is a sequence of standard conversions in the following order:
(1.1) — Zero or one conversion from the following set: lvalue-to-rvalue conversion, array-to-pointer conversion,
and function-to-pointer conversion.
(1.2) — Zero or one conversion from the following set: integral promotions, floating point promotion, integral
conversions, floating point conversions, floating-integral conversions, pointer conversions, pointer to
member conversions, and boolean conversions.
(1.3) — Zero or one qualification conversion.

但它并没有提到引用转换。在c++中广泛使用;例如:

代码语言:javascript
复制
auto ex = std::runtime_exception();
std::exception& ref = ex; //reference conversion


//reference to Derived converion to reference to Base in
// operator = call in object slicing
class B{};
class D : public B
{};
B b = d;

我也不知道原因?

EN

回答 1

Stack Overflow用户

发布于 2018-03-08 04:31:17

参见C++11标准中的§8.5.3?4:

对于给定的类型“cv1 T1”和“cv2 T2”,如果T1与T2相同,或者T1是T2的基类,则“cv1 T1”与“cv2 T2”是引用相关的。“cv1 T1”与“cv2 T2”是参考兼容的,如果T1与T2相关,并且cv1与cv2相同或更高。

在您的示例中,std::exceptionstd::runtime_exception的基类,这使得ref引用与ex相关。由于exref都不是constvolatile,所以它们具有相同的简历资格,并且refex参考兼容。

§8.5.3?5:

对“cv1 T1”类型的引用由“cv2 T2”类型的表达式初始化,如下所示:

-如果引用是左值引用和初始值设定项表达式

ref是一个左值引用,初始化器表达式ex是一个左值,我们已经确定refex的引用兼容。

与之相关的还有§8.5.3?5中的最后一句话

在我上面引用的例子中,引用被称为直接绑定到初始化器表达式。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42409152

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档