为什么编译器允许参考文献用于C 中的运行时间多态性



我关心的是运行时多态性。我非常了解使用基类指针和"虚拟"关键字来实现它的概念。而且我确实理解了为什么编译器防御者将决议调用为运行时。但是,我很困惑地思考为什么在使用引用而不是指针时,编译器会推迟它。一旦分配,参考就无法提及其他任何内容。那么,编译器是否已经知道引用指的是什么对象?那么,当有基础类参考而不是指针时,为什么不静态解析函数调用呢?对于指针而言,这是不同的,因为它可以在类层次结构内的运行时指向任何对象。但是参考已修复!

这是一个代码段:

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;
}

"引用是固定的"前提"是错误的。引用可以指层次结构中任何对象的基本子对象,就像指针所能一样。编译器无法从引用中分辨出最衍生的对象是什么,不超过指针。

考虑:

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"

最新更新