【发布时间】:2015-10-04 17:08:19
【问题描述】:
我正在尝试在 C++ 中使用运行时多态性。有人可以解释一下这个程序的输出吗?我运行它,它给了我一个 Derived 的输出(意思是调用了派生类的函数 f())。
另外,如果我取消注释语句,程序的预期行为是什么 - d.f(); ?
// Example program
#include <iostream>
#include <string>
class Base {
public :virtual void f(int a = 7){std::cout << "Base" <<std::endl;}
};
class Derived : public Base {
public :virtual void f(int a) {std::cout << "Derived" <<std::endl;}
};
int main() {
Derived d;
Base& b = d;
b.f();
//d.f();
return 0;
}
【问题讨论】:
-
如果您想确保您的
Derived::f()在您的Base::f()上按预期工作,您可以在函数声明之后使用关键字override,然后再执行它:virtual void f( int a ) override { std::cout << "Derived" << std::endl; }这将确保将调用预期派生的正确函数以提供所需的实现。
标签: c++ polymorphism