------
Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------
匿名变量:利用类创建一个对象的时候,没有将对象的地址交给一个指针变量保存,这样的对象称为匿名对象,即没有指针指向的对象。
//匿名变量1 #import <Foundation/Foundation.h>2 //类的声明3 @interface Car : NSObject4 {5 @public//表示允许外界指针间接访问对象的成员变量6 int _speed;//速度7 }8 //方法声明9 - (void)run;//跑10 @end1112 //类的实现13 @implementation Car14 //方法实现15 - (void)run16 {17 NSLog(@"速度为%d的车子跑起来了", _speed);18 }1920 @end2122 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、这里要求我们知道这个输出结果即可,不建议写匿名对象这样的代码。
本文探讨了Java中匿名对象的概念及其与实例化的区别。通过示例代码展示了如何创建匿名对象,并分析了其与普通对象在内存管理和生命周期上的不同。

675

被折叠的 条评论
为什么被折叠?



