仅覆盖虚拟方法

时间:2015-10-25 05:49:22

标签: c++ inheritance virtual-functions

我正在尝试理解C ++中的PropertyTypesAlias函数。我开始知道在派生类中,虚拟方法被派生类中给出的实现覆盖。

以下是我用来测试此代码的代码:

virtual

输出:

pure-virtual

这意味着#include <iostream> using namespace std; class Base { protected: int a; public : virtual void modify () { a=200; } void print () { cout<<a<<"\n"; } }; class Derived : public Base { int b; public : void modify() { a=100; b=10; } void print () { cout<<a<<"\t"<<b<<"\n"; } }; int main () { Base b; b.modify (); b.print (); Derived d; d.modify (); d.print (); return 0; } 也会与200 100 10 一起被覆盖。

我的问题:

那为什么我们需要虚拟方法......?

1 个答案:

答案 0 :(得分:3)

请考虑您的代码示例:

Base* b = new Derived();
b->modify();
b->print();

即使b指向Derived实例,虚拟方法b->modify的调用也会正确调用Derived::modify。但是,b->print的调用(未声明为虚拟)将打印200\n而不使用\t中的前导Derived::print字符。

相关问题