------
Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------
匿名变量:利用类创建一个对象的时候,没有将对象的地址交给一个指针变量保存,这样的对象称为匿名对象,即没有指针指向的对象。
//匿名变量1 #import <Foundation/Foundation.h>
2 //类的声明
3 @interface Car : NSObject
4 {
5 @public//表示允许外界指针间接访问对象的成员变量
6 int _speed;//速度
7 }
8 //方法声明
9 - (void)run;
//跑
10 @end
11
12 //类的实现
13 @implementation Car
14 //方法实现
15 - (void)run
16 {
17 NSLog(@"速度为%d的车子跑起来了", _speed);
18 }
19
20 @end
21
22 int main(int argc, const char * argv[])
23 {
24 /*
2<span style="font-family: consolas, 'Courier New', courier, monospace; white-space: pre-line;">5 Car *c; </span>
<span style="font-family: consolas, 'Courier New', courier, monospace; white-space: pre-line;">26 c = [Car new]; </span>
<span style="font-family: consolas, 'Courier New', courier, monospace; white-space: pre-line;">27 c->_speed = 250; </span>
<span style="font-family: consolas, 'Courier New', courier, monospace; white-space: pre-line;">28 </span>
<span style="font-family: consolas, 'Courier New', courier, monospace; white-space: pre-line;">29 [c run]; </span>
<span style="font-family: consolas, 'Courier New', courier, monospace; white-space: pre-line;">30 */ </span>
<span style="font-family: consolas, 'Courier New', courier, monospace; white-space: pre-line;">31 </span>
<span style="font-family: consolas, 'Courier New', courier, monospace; white-space: pre-line;">32 // 不要写类似匿名对象这样的代码 </span>
<span style="font-family: consolas, 'Courier New', courier, monospace; white-space: pre-line;">33 // 只要求能说出输出结果 </span>
<span style="font-family: consolas, 'Courier New', courier, monospace; white-space: pre-line;">34 [Car new]->_speed = 300; </span>
<span style="font-family: consolas, 'Courier New', courier, monospace; white-space: pre-line;">35 </span>
<span style="font-family: consolas, 'Courier New', courier, monospace; white-space: pre-line;">36 [[Car new] run]; </span>
<span style="font-family: consolas, 'Courier New', courier, monospace; white-space: pre-line;">37 </span>
<span style="font-family: consolas, 'Courier New', courier, monospace; white-space: pre-line;">38 return 0; </span>
<span style="font-family: consolas, 'Courier New', courier, monospace; white-space: pre-line;">39 }</span>
分析:
1、如果将34-36行注释掉,打开24-30行;表示创建了一个对象c,并给对象c的成员变量_speed赋值250,然后对象c调用对象方法run,输出结果为:
速度为250的车子跑起来了
2、如果注释掉24-30行,打开34-36行;
第34行表示:创建一个Car类型的匿名对象,并对该匿名对象的成员变量_speed赋值300
第36行[[Car new] run];这里又出现一个[Car new],说明在这里又创建了一个新的匿名对象(并不是第34行创建的匿名对象),新匿名对象由于没有赋值,默认初始化为0,调用run方法,输出结果为:速度为0的车子跑起来了
3、这里要求我们知道这个输出结果即可,不建议写匿名对象这样的代码。