父类子类普通函数与虚函数调用问题

考点:父类指针指向子类实例对象,调用普通重写方法时,会调用父类中的方法。而调用被子类重写虚函数时,会调用子类中的方法。

 1 class A
 2 {
 3 public:
 4  void FuncA()
 5  {
 6      printf( "FuncA called\n" );
 7  }
 8  virtual void FuncB()
 9  {
10      printf( "FuncB called\n" );
11  }
12 };
13 class B : public A
14 {
15 public:
16  void FuncA()
17  {
18      A::FuncA();
19      printf( "FuncAB called\n" );
20  }
21  virtual void FuncB()
22  {
23      printf( "FuncBB called\n" );
24  }
25 };
26 void main( void )
27 {
28  B  b;
29  A  *pa;
30  pa = &b;
31  A *pa2 = new A;
32  pa->FuncA(); ( 333  pa->FuncB(); ( 434  pa2->FuncA(); ( 535  pa2->FuncB();
36  delete pa2;
37 }

运算结果:

FuncA called
FuncBB called
FuncA called
FuncB called

 pa->FuncA(); ( 3)//pa=&b动态绑定但是FuncA不是虚函数,所以FuncA called
 pa->FuncB(); ( 4)//FuncB是虚函数所以调用B中FuncB,FuncBB called  
 pa2->FuncA(); ( 5)//pa2是A类指针,不涉及虚函数,调用的都是A中函数,所以FuncA called FuncB called
 pa2->FuncB()
 
再次说明了,子类中被重写的虚函数的运行方式是动态绑定的,与当前指向类实例的父类指针类型无关,仅和类实例对象本身有关。

猜你喜欢

转载自www.cnblogs.com/lyqf/p/12515920.html
今日推荐