java为什么不需要指针_为什么我要使用指针而不是对象本身?

对于这个问题有许多很好的答案,包括前向声明、多态性等重要的用例。但是,我觉得你的问题的“灵魂”的一部分没有得到回答-即跨Java和C+的不同语法意味着什么。

让我们来看看比较这两种语言的情况:

Java:Object object1 = new Object(); //A new object is allocated by JavaObject object2 = new Object();

//Another new object is allocated by Javaobject1 = object2; //object1 now points to the object originally allocated for object2

//The object originally allocated for object1 is now "dead" - nothing points to it, so it//will be reclaimed by the Garbage Collector.

//If either object1 or object2 is changed, the change will be reflected to the other

与此最接近的是:

C+:Object * object1 = new Object(); //A new object is allocated on the heapObject * object2 = new Object();

//Another new object is allocated on the heapdelete object1;

//Since C++ does not have a garbage collector, if we don't do that, the next line would

//cause a "memory leak", i.e. a piece of claimed memory that the app cannot use

//and that we have no way to reclaim...object1 = object2; //Same as Java, object1 points to object2.

让我们看看另一种C+方式:Object object1; //A new object is allocated on the STACKObject object2; //Another new object is allocated on the STACKobject1 = object2;

//!!!! This is different! The CONTENTS of object2 are COPIED onto object1,//using the "copy assignment operator", the definition of operator =

.//But, the two objects are still different. Change one, the other remains unchanged.

//Also, the objects get automatically destroyed once the function returns...

最好的思考方法是-或多或少-Java(隐式)处理指向对象的指针,而C+可以处理指向对象的指针或对象本身。这是有例外的-例如,如果您声明Java“基元”类型,它们是被复制的实际值,而不是指针。所以,

Java:int object1; //An integer is allocated on the stack.int object2; //Another integer is allocated on the stack.object1 = object2;

//The value of object2 is copied to object1.

也就是说,使用指针并不一定是正确或错误的处理方法;然而,其他答案已经令人满意地涵盖了这一点。但是,总的想法是,在C+中,您可以更多地控制对象的生存期,以及对象的生存位置。

带回家点.Object * object = new Object()构造实际上最接近于典型的Java(或C#)语义。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值