zoukankan      html  css  js  c++  java
  • 父类子类构造函数的执行顺序

    代码
        class Program
        {
            
         
    class A
         {
              
    public A(){
                    PrintFields();
               }
              
    public virtual void PrintFields(){}
          }
         
    class B : A
         {
             
    int x = 1;
             
    int y;
             
    public B()//new B()时会先new父对象A
             {
                 y 
    = -1;
             }
             
    public override void PrintFields()
             {
                 Console.WriteLine(
    "x={0},y={1}", x, y);
             }
         }

            
    static void Main(string[] args)
            {
                B b 
    = new B();
                
    // 当使用new B()创建B的实例时,产生什么输出?
                
    // 答案:输出为x=1,y=0
                
    //(继承的子类在new时,先new父类对象,然后new自身私有成员,当调用b.PrintFields()时,则输出x=1,y=-1)

            }
        }
    代码
    namespace ConsoleApplication2
    {
        
        
    class A
        {
            
    public static int X;
            
    static A()
            {
                X 
    = B.Y + 1;
            }
        }
        
    class B
        {
            
    public static int Y = A.X + 1//执行该语句时,会先执行A的构造函数
            static B() { }
            
    static void Main()
            {
                Console.WriteLine(
    "X={0},Y={1}", A.X, B.Y);
                
    //产生的输出结果是什么? X=1,Y=2

            }
        }

    }
  • 相关阅读:
    Paratroopers 最大流问题 dinic算法 水平有待提高
    Food Delivery 区间dp
    D
    Codeforces 1282A Temporarily unavailable
    PAT 顶级 1017 The Best Peak Shape (35分)(最长上升子序列)
    POJ 2217 Secretary(后缀数组+高度数组)
    团体程序设计天梯赛 L1-011~L1-015
    PAT顶级解题目录
    PAT顶级 1005 Programming Pattern (35分)(后缀数组+基数排序 或 字符串哈希)
    团体程序设计天梯赛 L1-006~L1-010
  • 原文地址:https://www.cnblogs.com/hubcarl/p/1675325.html
Copyright © 2011-2022 走看看