zoukankan      html  css  js  c++  java
  • 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在同一继承层次的同一个类中,构造函数可以重载

  • 相关阅读:
    [Swift]LeetCode895. 最大频率栈 | Maximum Frequency Stack
    [Swift]LeetCode894. 所有可能的满二叉树 | All Possible Full Binary Trees
    [Swift]LeetCode893. 特殊等价字符串组 | Groups of Special-Equivalent Strings
    [Swift]LeetCode892. 三维形体的表面积 | Surface Area of 3D Shapes
    [Swift]LeetCode891. 子序列宽度之和 | Sum of Subsequence Widths
    [Swift]LeetCode890. 查找和替换模式 | Find and Replace Pattern
    find missing conjunction, why?
    sh 脚本报错
    What's mean ORA-25191?
    饼状图
  • 原文地址:https://www.cnblogs.com/zyip/p/2663139.html
Copyright © 2011-2022 走看看