Late binding occurs only with virtual functions, and only when you’re using an address of the base class where those virtual functions exist.
这是一本著名教科书的摘录。
我的问题是......作者所说的“使用地址”到底是什么意思?
最佳答案
背景
相关场景是当你有一个指针或引用是静态类型的pointer-to-Base或reference-to-Base,不管指针或引用是局部变量、函数参数、成员变量等..
// accessed via pointer...
Base* p = new Derived(); p->fn(); // (ref.1)
void f(Base* p) { p->fn(); } Derived d; f(&d);
// accessed via reference...
const Base& r = static_derived;
void f(Base& b) { b.fn(); } Derived d; f(d);
Late binding occurs only with virtual functions, and only when you’re using an address of the base class where those virtual functions exist.
该声明在两个方面具有误导性:
延迟绑定(bind)可能发生在特定情况下,但如果优化器可以计算出所涉及的动态类型,则允许优化器在编译或链接时进行绑定(bind)。例如,如果上面 (ref.1) 中的两行代码一起出现在一个函数体中,编译器可以辨别出
p
寻址一个Derived
对象并硬编码一个调用直接到任何Derived::fn()
覆盖,或者基类实现失败。上述情况涉及指针和引用。就 C++ 标准而言,用于实现引用的机制未指定,我们谦虚的程序员不应该假设它们是使用不同符号的有效指针,所以我们不应该认为它们存储“地址”它们引用的变量,但将它们视为存储地址的美化指针通常是实用的,引用的语句将它们与指针混为一谈,作为“使用地址”的机制。
关于c++ - 这在虚函数中意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29405832/