当我引用子类作为抽象基类类型时会发生什么

问题描述

#include <iostream>
using namespace std;

class A {
public:
    virtual void f() = 0;
};

class B : public A {
public:
    void f() {cout << "hi" << endl;}

    void g() { cout << "bye" << endl; }
};

int main() {
    B b;
    A &a = b;
    a.f(); // prints "hi"
    a.g(); // compile error no member g()
    return 0;
}

a.g()调用B的f()时,为什么a.f()给出编译错误? 在A &a = b;,编译器是否以某种方式设置a的别名存储结束的边界?

解决方法

您正在尝试从g()的实例调用AA没有g()的实现,因此无法通过A对象调用它。 a是对B的引用,这一事实不能使a访问A不知道的任何功能。

另一方面,

B is A,它定义了虚函数f()的实现,因此引用{{1} }调用正确的函数。