using System;//using 指令 它引用了system命名空间
using System.Collections.Generic;
using System.Text;
using Acme.Collections;namespace Acme.Collections
{ class Program
{
static void Main(string[] args)
{
third t = new third(); }
}
public class first
{
public first()
{
System.Console.WriteLine("I am first constructor"); }
public static int n3=0; static first()
{ n3=third.n1+second.n2+1;
System.Console.WriteLine("I am first static constructor"+first.n3);
} }
public class second : first
{
public second()
{
System.Console.WriteLine("I am second constructor");
}
public static int n2=0;
static second()
{ n2=third.n1+1;
System.Console.WriteLine("I am second static constructor"+second.n2);
}
}
public class third : second
{
public static int n1= 0;
public third()
{
System.Console.WriteLine("I am third constructor");
} static third()
{
n1= 1;
System.Console.WriteLine("I am third static constructor"+third.n1);
} }在vs2005中 按F11 只能看到非静态的构造函数执行。但结果上有静态构造函数里的语句,在有静态和非静态构造函数时先执行静态的??再加上继承我都晕了,希望高手帮我分析下程序执行的步骤
}
using System.Collections.Generic;
using System.Text;
using Acme.Collections;namespace Acme.Collections
{ class Program
{
static void Main(string[] args)
{
third t = new third(); }
}
public class first
{
public first()
{
System.Console.WriteLine("I am first constructor"); }
public static int n3=0; static first()
{ n3=third.n1+second.n2+1;
System.Console.WriteLine("I am first static constructor"+first.n3);
} }
public class second : first
{
public second()
{
System.Console.WriteLine("I am second constructor");
}
public static int n2=0;
static second()
{ n2=third.n1+1;
System.Console.WriteLine("I am second static constructor"+second.n2);
}
}
public class third : second
{
public static int n1= 0;
public third()
{
System.Console.WriteLine("I am third constructor");
} static third()
{
n1= 1;
System.Console.WriteLine("I am third static constructor"+third.n1);
} }在vs2005中 按F11 只能看到非静态的构造函数执行。但结果上有静态构造函数里的语句,在有静态和非静态构造函数时先执行静态的??再加上继承我都晕了,希望高手帮我分析下程序执行的步骤
}
1.一个类的静态构造函数在使用到该类时,将会被首先初始化。
2.一个字类的构造函数在被调用时,会先调用该类的父类构造函数。因此本代码的执行顺序:
执行静态构造函数:third.static third()
执行非静态构造函数 third.third(),此时将会先执行该类的父类构造函数:
--自动调用父类静态函数second.static second()
--自动调用父类非静态函数second.second() ,此时将会先执行该类的父类构造函数:
--自动调用父类静态函数first.static first()
--自动调用父类非静态函数first.first()
--执行second类非静态函数体second.second()
执行非静态构造函数 third.third()函数体
静态的先执行,我执行了一下输出的结果是:
I am third static constructor1
I am second static constructor2
I am first static constructor4
I am first constructor
I am second constructor
I am third constructor
因为实例化的是third
所以执行顺序是:
static third()
static second()
static first()
public first()
public second()
public third()
构造:
全局->静态->局部
析构顺序相反!!!建议在去重新读c++的构造函数等章节!!!