为什么编译器允许引用用于 C++ 中的 运行 时间多态性?

Why does the compiler allow references to be used for run-time polymorphism in C++?

我担心的是 运行 时间多态性。我非常理解使用 base-class 指针和 "virtual" 关键字来实现它的概念。而且我确实理解为什么编译器将调用解析推迟到 运行 时间。但是,我很困惑为什么编译器会在使用引用而不是指针时推迟它。引用一旦分配,就不能引用任何其他内容。那么,编译器不是已经知道引用指的是什么对象了吗?那么,当存在 base-class 引用而不是指针时,为什么它不静态解析函数调用呢? 这与指针不同,因为它可以指向 class 层次结构中 运行 时间的任何对象。但是引用是固定的!

这是一个代码片段:

class Base
{
protected:
   int m_value;

public:
   Base(int value)
    : m_value(value)
   {
  }

   virtual const char* getName() const { return "Base"; }
   int getValue() const { return m_value; }
};

class Derived: public Base 
{
public:
   Derived(int value)
       : Base(value)
  {
   }

virtual const char* getName() const { return "Derived"; }
};

int main()
{
   Derived derived(5);
   std::cout << "derived is a " << derived.getName() << " and has value " << 
   derived.getValue() << '\n';

Base &ref = derived;
std::cout << "ref is a " << ref.getName() << " and has value " << ref.getValue() << '\n';

Base *ptr = &derived;
std::cout << "ptr is a " << ptr->getName() << " and has value " << ptr- >getValue() << '\n';

return 0;
}

"The reference is fixed"前提是假的。引用可以引用层次结构中任何对象的基础子对象,就像指针一样。编译器无法从引用中分辨出 most-derived 对象是什么,就像从指针中一样。

考虑:

void DoSomething(const Base& b) { std::cout << b.getName(); }

Base base;
DoSomething(base);  // b is bound to Base object. Prints "Base"

Derived derived;
DoSomething(derived);  // b is bound to Base subobject of Derived object.
                       // Prints "Derived"