c++标准说标准转换包括
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++中广泛使用;例如:
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;我也不知道原因?
发布于 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::exception是std::runtime_exception的基类,这使得ref引用与ex相关。由于ex和ref都不是const或volatile,所以它们具有相同的简历资格,并且ref与ex参考兼容。
§8.5.3?5:
对“cv1 T1”类型的引用由“cv2 T2”类型的表达式初始化,如下所示:
-如果引用是左值引用和初始值设定项表达式
ref是一个左值引用,初始化器表达式ex是一个左值,我们已经确定ref与ex的引用兼容。
与之相关的还有§8.5.3?5中的最后一句话
在我上面引用的例子中,引用被称为直接绑定到初始化器表达式。
https://stackoverflow.com/questions/42409152
复制相似问题