geeksforgeeks-047-派生类中的虚函数

在C++中,一旦一个基类中的成员函数被声明为虚函数,那么它在每个派生类中都是虚函数。
因此,当在子类中重定义基类的虚函数时,没有必要在派生类中使用virtual关键字。
如下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include<iostream>

using namespace std;

class A {
public:
virtual void ()
{ cout<<"n A::fun() called ";}

};

class B: public A {
public:
void ()
{ cout<<"n B::fun() called "; }

};

class C: public B {
public:
void ()
{ cout<<"n C::fun() called "; }

};

int main()
{
C c;
B *b = &c; // A pointer of type B* pointing to c
b->fun(); // this line prints "C::fun() called"
getchar();
return 0;
}

程序输出“C::fun() called”,因为B::fun()自动变为虚函数了。