the constructor in C# (面试题构造函数是否可以继承和重载的解释)

1.观察两个类

  class A
    {
        protected int i = 0;
        public A()
        {
            i = 1;
        }

        public void P()
        {
            System.Console.WriteLine("P:"+i.ToString());
        }

        public virtual void VP()
        {
            System.Console.WriteLine("VP in A:" + i.ToString());
        }
    }

    class B:A
    {
        public B()
        {
            i = 2;
        }

        public B(int i)// public B(int i) = public B(int i):base()
        {
            //this.i = i;
            
//keep this section as empty, while the base constructor will be invoked
        }

        public override void VP()
        {            
            System.Console.WriteLine("VP in B:" + i.ToString());
            //base.VP();
        }

    } 

 

2.

            A b = new A();
            b.P();
            b.VP();
            Console.Read();
            //调用默认构造函数
            
//调用虚方法
            
//一切都很简单而且美好


            A b1 = new B();
            b1.P();
            b1.VP();
            //调用派生类的构造函数 , 
            
//派生类的构造函数调用基类的默认构造函数

            A b2 = new B(0);
            b1.P();
            b1.VP();
            //调用派生类中带参数的构造函数时 public B(int i) = public B(int i):base()
            
//先调用派生类的构造函数
            
//派生类的构造函数调用基类的默认构造函数

//            有调用堆栈为证
//>    ConsoleApplication2.exe!ConsoleApplication2.A.A() 行 11    C#
//    ConsoleApplication2.exe!ConsoleApplication2.B.B() 行 30 + 0x8 字节    C#
//    ConsoleApplication2.exe!ConsoleApplication2.Program.Main(string[] args = {string[0]}) 行 64 + 0x15 字节    C#


            

 

结论: 

1构造函数无法用virtual和override修饰,会造成编译错误
2父构造函数可以被修改,但不是重写,也不是重载,而是在调用时注入了新函数的代码 

3在同一继承层次的同一个类中,构造函数可以重载

 

posted @ 2012-08-30 09:56  zyip  阅读(1091)  评论(3编辑  收藏  举报