【问题标题】:What happens when I make reference to subclass as a abstract base class type当我将子类引用为抽象基类类型时会发生什么
【发布时间】:2021-01-25 18:09:11
【问题描述】:
#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()a.f() 调用B 的f() 时出现编译错误? 在A &amp;a = b;,编译器是否以某种方式设置了 a 的别名内存结束的边界?

【问题讨论】:

    标签: c++ inheritance reference abstract-class


    【解决方案1】:

    您正试图从A 的实例调用g()A 没有g() 的实现,所以不能通过A 对象调用。 a 是对 B 的引用这一事实不会让 a 访问 A 不知道的任何功能。

    B,另一方面 is-a A,并定义了虚函数 f() 的实现,因此引用 a 调用正确的函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-21
      • 1970-01-01
      • 2018-09-20
      • 2015-04-07
      相关资源
      最近更新 更多