问题描述
#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()
的实例调用A
。 A
没有g()
的实现,因此无法通过A
对象调用它。 a
是对B
的引用,这一事实不能使a
访问A
不知道的任何功能。
B
是 is A
,它定义了虚函数f()
的实现,因此引用{{1} }调用正确的函数。