众所周知,下面的代码片段打印出 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 astd::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/