解释对象变量的声明和赋值 [英] Explain object variable declaration and assignment

查看:67
本文介绍了解释对象变量的声明和赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个片段中:

NSString *testString; 
testString = [[NSString alloc] init]; 

为什么,在第二行,我们不必编写 *testString = ... 来访问它实际指向的位置?

Why, on the second line, do we not have to write *testString = ... in order to access the location where it's actually pointing?

在第一行之后,什么是*testString,什么是testString?

After the first line, what is *testString and what is testString?

推荐答案

为什么,在第二行,我们不必编写 *testString = ... 来访问它实际指向的位置?

Why, on the second line, do we not have to write *testString = ... in order to access the location where it's actually pointing?

init 方法返回一个指向对象的通用指针——它的返回类型是 id.testString 是一个指向 NSString 的指针,它是一个对象,所以你分配了一个指向另一个指针的指针.取消引用分配给的指针会导致类型不匹配.

The init method returns a generic pointer to an object -- its return type is id. testString is a pointer to an NSString, which is an object, so you are assigning a pointer to another pointer. Dereferencing the assigned-to pointer would be a type mismatch.

变量名是放置东西的地方(内存地址的标签).变量的类型是你可以放在那里的东西.在指针的情况下,你放入它的东西也是一个内存地址.为了获得该地址,您可以取消对指针的引用.您可以在该地址中放入的东西与您在指针本身中放入的东西不同.

A variable name is a place (a label for a memory address) in which to put something. The type of the variable is the kind of thing that you can put there. In the case of a pointer, the kind of thing that you put in it is also a memory address. In order to get that address, you dereference the pointer. The kind of thing that you can put at that address is different from the kind that you put in the pointer itself.

在第一行之后,什么是*testString,什么是testString?

After the first line, what is *testString and what is testString?

在第一行之后,*testString,或者testString 指向的东西,是垃圾(实际上是未定义的).testString 是一个指向内存地址的指针(4 或 8 个字节,取决于您的系统),它也是未定义的.

After the first line, *testString, or the thing at which testString points, is garbage (actually undefined). testString is a pointer (4 or 8 bytes depending on your system) to a address in memory, and it is also undefined.

在第二行之后,*testString 是一个 NSString 对象.testString 仍然是一个指向地址的指针,其中有一个有效的 NSString 对象.

After the second line, *testString is an NSString object. testString is still a pointer to an address, where there is a valid NSString object.

这篇关于解释对象变量的声明和赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆