您的位置:首页 > 编程语言 > C语言/C++

JAVA C# C/C++之比较学:初始化顺序

2015-11-13 22:12 661 查看
1、java

java没有全局变量。在包含main类中声明的static final会最先被初始化。在每一个类被实例化的时候,其所包含的static final都会被初始化。然后执行构造函数。java一般采用static final来表示初始化的全局变量。

public class TestInitOrder {

public static final GlobalParam m_i = new GlobalParam();
public static void main(String[] args) {
System.out.println("this is main method");

}
}

class GlobalParam{
public static final LocalParam m_i = new LocalParam();
public GlobalParam(){
System.out.println("this is the init of global param");
}
}
class LocalParam{
public LocalParam(){
System.out.println("this is the init of local param");
}
}

上述程序的输出为

this is the init of local param

this is the init of global param

this is main method

在java的类成员中,为static可以为其初始化也可以不为其初始化,static final必须为其初始化,而非static变量不能为其进行初始化。对static的成员变量的初始化和static final的顺序相同。额外说一句,所有static声明的变量都被存放在数据区(data segment)。

java中一般不使用析构函数。

2、C#

C#也没有全局变量的概念。

和java类似:若类中有main函数,则需要初始化的static先进行初始化,后运行main函数。若没有main函数,则先进行static变量先进行初始化,然后运行构造函数

using System;

namespace sandbox
{
class class1
{
static int i = getNum();

public class1()
{
Console.WriteLine("this is constructor of class1");
}
static int getNum()
{
Console.WriteLine("this is static param init of class1");
return 1;
}
static void Main(string[] args)
{

Console.WriteLine("this is main");
class1 a = new class1();
class2 b = new class2();
Console.Read();

}

}
class class2
{
static int i = getNum();

public class2()
{
Console.WriteLine("this is constructor of class2");
}
static int getNum()
{
Console.WriteLine("this is static param init of class2");
return 1;
}

}

}


除非打开了代码中的非托管,否则不需要写析构函数。

3、C\C++

在c++中,全局变量被存储在全局变量,静态变量存储区。c++的main函数不能写在类里面。

#include "stdafx.h"
#include <iostream>
class A
{
public:
A()
{
std::cout << "this is init of A" << std::endl;
}
};
class B
{
public:
B()
{
std::cout << "this is init of B" << std::endl;
}
};
class D
{
public:
D()
{
std::cout << "this is init of D" << std::endl;
}
};
class C
{
public:
D *d = new D();
C()
{
std::cout << "this is init of C" << std::endl;
}

};
A *a = new A();
B b;
int main()
{
std::cout << "this is main" << std::endl;
static C *c = new C();
system("pause");

return 0;

}
上述初始化顺为ABmainDC。显然,类内的变量初始化要先于类的构造函数。


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: