【发布时间】:2013-04-07 15:57:38
【问题描述】:
以下代码有问题:最后一行应该是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);
}
【问题讨论】:
-
在驱动类
void g(int ??)缺少变量名。 -
@GrijeshChauhan 该变量未使用,因此不需要名称。
-
@juanchopanza 好的,我刚刚注意到
-
您只能从指向
Base的指针调用Base的公共接口中的方法,但调用会被分派到派生类型。
标签: c++ virtual overriding