c++ - 为什么对多态类的引用是多态的?

标签 c++ polymorphism language-lawyer

众所周知,下面的代码片段打印出 Derived 或类似的内容。

#include<iostream>
#include<typeinfo>
class Base { public: virtual ~Base(){} };
class Derived : public Base{};
int main()
{
     Derived d;    
     Base& b = d;
     std::cout << typeid(b).name() << '\n';
}

但我想了解如何从标准 (N4140) 的第 §5.2.8/2 段得出结论。比如b肯定是一个glvalue,但是类型Base&Base不一样,所以我不能说b 是多态的。我错过了什么?

最佳答案

来自[表达式]

If an expression initially has the type “reference to T” (8.3.2, 8.5.3), the type is adjusted to T prior to any further analysis. The expression designates the object or function denoted by the reference, and the expression is an lvalue or an xvalue, depending on the expression.

表达式 b 初始类型为“对 Base 的引用”,因此类型调整为 Base。它是一个左值,也就是一个左值。

来自[class.virtual]:

A class that declares or inherits a virtual function is called a polymorphic class.

Base声明了一个虚函数,所以它是一个多态类。

来自 [expr.typeid]:

When typeid is applied to a glvalue expression whose type is a polymorphic class type (10.3), the result refers to a std::type_info object representing the type of the most derived object (1.8) (that is, the dynamic type) to which the glvalue refers.

综上所述,我们满足初始条件(表达式是一个泛左值,其类型是多态类类型),所以我们选择b所指向的最派生对象。那将是 d,其类型为 Derived

如果 b 是一个 Base 而不是 Base&,那么最派生的对象将是 b 本身.

关于c++ - 为什么对多态类的引用是多态的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31708731/

相关文章:

c++ - 如何正确组织继承类以利用多态性?

c++ - map 不能用作 C++ 中的数组样式打印吗?

c++ - 初始化成员变量

c++ - 为什么 C++ 将 unsigned char 值打印为负数?

c - 通过结构别名数组

c++ - 大括号初始值设定项列表作为函数参数

c++ - 不使用违规表达式时的未定义行为?

c++ - 这个 while 循环 (C++) 有什么问题?

c++带有嵌套多态模板的动态转换

c++ - make_shared 和抽象多态性