以下代码有bug:最后一行应该是
bp->g();
问题是,如果我注释掉那行,bp->f()
实际上调用了Derived版本,所以我假设编译器将bp视为类Derived,那么为什么在调用g时,编译器将bp
其视为Base指针。
谢谢!
#include <iostream>
using namespace std;
class Base {
public:
virtual void f() const { cout << "Base::f()\n"<< endl; }
virtual void g() const { cout << "Base::g()\n"<< endl; }
};
class Derived : public Base {
public:
void f() const {cout << "Derived::f()" << endl; }
void g(int) const {cout << "Derived::g()" << endl; }
};
int main() {
Base* bp = new Derived;
bp->f();
bp->g(1);
}