面试中关于虚函数的一道试题.

  1. //看了CSDN上面网友发的一道面试题.感觉自己的确该学习一下基础知识了.


  2. public class Examine
  3.     {
  4.         public Examine()
  5.         {
  6.             PrintFields(); 
  7.         }
  8.         public virtual void PrintFields() { } 
  9.     }
  10.     public class B:Examine
  11.     {
  12.         int x = 1;
  13.         int y;
  14.         public B()
  15.         {
  16.             y = -1;
  17.         }
  18.         public override void PrintFields()
  19.         {
  20.             Console.WriteLine("x={0},y={1}", x, y);
  21.             Console.ReadLine();
  22.         }
  23.     }


在new B()的时候,由于B继承于Examine ,因此会执行Examine中的构造函数来执行PrineFields()的方法.但是由于PrintFileds()是虚方法,在B中重载了一次.因为会输出 1 与 0, 而不是1和-1

这里是关于虚函数的一些比较容易理解的说法.
例如有两个类人员和老师,老师是人员的子类。人员中有一个虚函数DisplayInfo用来显示信息。但是,老师类有自己的成员函数也叫DisplayInfo,并且参数相同,用于显示老师的信息。在C++中如果有一个老师对象,它是由一个人员的指针指向的(父类指针可以指向子类对象),则当调用DisplayInfo函数时会直接调用老师的DisplayInfo,而不调用人员的DisplayInfo。如果不是DisplayInfo虚函数,上面的情况就会调用人员的DisplayInfo。

你可能感兴趣的:(面试中关于虚函数的一道试题.)