实例化值类型 [英] Instantiating a value type
问题描述
我在第一种情况下声明一个int类型的变量,在第二种情况下我实例化了相同的变量,以下是两种情况:
案例1:
int a;
a = 10;
现在我实例化一个int类型的变量
情况2:
int a = new int();
a = 10;
以上两种情况有什么区别,内部到底发生了什么.
问候
Chaithu
Hi,
I declare a variable of type int in the first case and in the second case i instantiate the same,Below are the 2 cases :
case1:
int a;
a=10;
Now I instantiate a variable of type int
Case 2:
int a =new int();
a=10;
what is the difference between the above two cases,what exactly happens internally.
Regards
Chaithu
推荐答案
我相信在情况1中,变量声明为没有值,然后分配为"10".
在情况2中,变量使用其默认值(为"0")声明,然后分配为"10".
但这只是我的2美分.
I believe that in case 1, the variable is declared without a value and then assigned ''10''.
In case 2 the variables is declared with it''s default value (which is ''0'') and then assigned ''10''.
But that''s just my 2 cents.
要解释您的问题,请看下面的示例.
To explain your question, look at the example below.
struct Person
{
public Person(int age)
{
this.Age = age + 10;
}
public int Age;
}
然后像访问它一样
And then access it like
Person person =new Person();
person.Age = 10;
Person person1 = new Person(10);
您期望Person的年龄为10,但是Person1的值为20.使用new
关键字可以调用特定的构造函数.对于第二种情况,您要调用默认构造函数,该构造函数将0分配给变量,然后将其分配值.在第一种情况下,int会接受与值类型隐式兼容的值.
对于int,调用的两种方式是相同的,因为您只是使用默认的构造函数.
希望这会有所帮助.
注意:值类型与引用类型不同在上面的示例中,如果此人是class
,则
Person1= Person; Person1.Age=30; then Person.Age also equals 30
.但如果是值类型,则Person.Age将具有原始值.值类型存储在堆栈中,新变量将位于新的内存地址中.参考变量指针位于堆栈中,该指针指向堆中的地址.因此,两个变量可以在堆中保存一个公共地址.
祝你好运
What you expect Person''s age is 10, but Person1''s value will be 20. Using the new
key word you can call a specific constructor. For your second case you are calling a default construtor which assign a 0 to the variable and then you are assigning value to it. In the first case the int will accept a compatible value which implicitly to the value type.
For the int, the both ways you are calling are same, because you are using simply a default constructor.
Hope this helps.
Note: value types are different from reference types In the above example if the person is a class
then
Person1= Person; Person1.Age=30; then Person.Age also equals 30
. But in case of value type Person.Age will have the original value. Value types stores on the stack and a new variable will be in a new memory address. Reference variable pointers are in the stack which points to an address in the heap. So two variable can hold a common address in the heap.
Good luck
查看此链接
http://www.coderanch.com/t/468841/java/java/difference-between-int-maxrows-Integer [ ^ ]
see this link
http://www.coderanch.com/t/468841/java/java/difference-between-int-maxrows-Integer[^]
这篇关于实例化值类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!