2010-10-13 140 views
0

如果我使用类的类型创建变量,那么我将初始化它的实际值是多少?我的意思是 - int是用数字类型的值初始化的。但是就技术精度而言,当我创建类的新实例时会发生什么?声明类实例及其初始化

class a 
{ 
} 
class b 
{ 
    a InstanceOfA; 
    InstanceOfA=new(); //which what I initialize the variable? 
} 

希望你会明白我的意思,感谢

回答

0

我不知道我得到了你的要求,但如果我did-
当初始化类,它的名字被赋予它的参考地址。
所以,当你写

InstanceOfA = new a(); 

InstanceOfA获得内存中的地址(在堆上..)的类型的对象。

3

您想创建一个新的类a实例。这里有一个例子,为了方便阅读,重命名类。

class MyClassA { 
} 

class MyClassB { 
    MyClassA a = new MyClassA(); 
} 

如果你的类需要进行一些初始化,实现了它的构造函数:

class MyClassA { 
    public MyClassA() { 
     // this constructor has no parameters 
     Initialize(); 
    } 

    public MyClassA(int theValue) { 
     // another constructor, but this one takes a value 
     Initialize(theValue); 
    } 
} 

class MyClassB { 
    MyClassA a = new MyClassA(42); 
} 
0

你这样的事情后,很可能是:

public class A 
{ 
} 

public class B 
{ 
    public static void Main(string[] args) 
    { 
     // Here you're declaring a variable named "a" of type A - it's uninitialized. 
     A a; 
     // Here you're invoking the default constructor of A - it's now initialized. 
     a = new A(); 
    } 
} 
0

一类的成员变量是使用其类型的默认值进行初始化。对于参考类型,这意味着它被初始化为null

要创建类的实例,你只需使用类名称:

InstanceOfA = new a();