关于java和c++里面 “类 = 类” 的区别

实验发现,java中的   类 = 类 与c++里面的  类 = 类  有着很大的不同
比如java中:
public class people{

 public int jjSize=0;

 public people(int jjSize){
  this.jjSize=jjSize;
 }

 public int getJJSize(){
  return jjSize;
 }

 public void setJJSize(int jjSize){
   this.jjSize=jjSize;  
 }
 
}这里定义一个people类

如果有poeple A=new people(800);
           people B=new people(999);
然后让A=B,A.setJJSize(2);
再print(B.jjSize);
会发现输出的结果是2
这里就说明java中的等于号意味着等号两边的类共用一个内存空间,是实质意义上的相等,即同一个个体

(=    =)*******那是不是该疑惑一下ArrayList里面的add方法?

既然  = 代表的是地址的相等,那
如果是类似下面这种情况,add的东西会不会都被删掉?

eg.
ArrayList list=new ArrayList();
 
 for(int i=0;i<9;i++){
  people CaiYingWen=new people(i);
  list.add(CaiYingWen);
  System.out.print(CaiYingWen.getJJSize()+" ");
 }/******************讲道理在局部new出来的CaiYingWen应该在循环尾被释放地址
 
 System.out.print("\n");
 for(int i=0;i<9;i++){
  System.out.print(((people) list.get(i)).getJJSize()+" ");
 }


但,输出发现两行都是 0,1,2,3,4,5,6,7,8
这就说明了,
我们想多了。。应该是有Array在用到ta,所以没释放地址

在C++中
poeple A(800);
people B(999);
然后让A=B,A.setJJSize(2);
再cout<<B.jjSize;
会发现输出的结果是999
如果输出A.jjSize;
其结果也是999


这就说明了,c++里面的 = 号不是复制地址,A就是A
B就是B,= 只是让A与B的内容相等,实质上不是同一个个体

那怎样使 = 两边的类代表同一个体?
比如这里实现一个简单的容器,有Add()和GetElement()的两个功能,类似java


template <class t>
class MyArray{
public:
 struct Node{
  t* p=NULL;
  Node* next=NULL;
 };
 Node begin;
 Node* cur = &begin;
 void Add(t &obj){
  Node *temp = new Node[sizeof(Node)]; 
  if (begin.next == NULL){
   begin.next = temp;
   begin.p = &obj;
   cur = temp;
  }
  else{
   (*cur).next = temp;
   (*cur).p = &obj;
   cur = temp;
  }

 }
 
 
 t& GetElement(int n){
  if (begin.p != NULL){
   Node* explore = &begin;
   for (int i = 1; i <= n; i++)
   {
    explore = (*(explore)).next;
   }
  // t temp = *((*explore).p);
   return *((*explore).p);
  }
  else{
   //return NULL;
  }
 }
};

比如这里我希望 t xxx=Array.GetElement(i)后,xxx与返回的东西是同一个个体(有些游戏中需要用到),类似java,那怎么办?

那就只能用指针了(不知道还有没有什么方法)。
用 t*  ptr=&(Array.GetElement(i));
然后*ptr  就代表同一个体了



猜你喜欢

转载自blog.csdn.net/qq_37960007/article/details/72783256
今日推荐