对象使用的两种方法

使用对象的两种方式:

  ——栈中的对象:

  CStudent stu;
  stu.setAge(14);
  cout<<"Age is :" << stu.getAge();

  ——堆中的对象:

  • 使用new/delete
  CStudent * pStu;
  pStu->setAge(14);
  cout<<"Age is :" << pStu->getAge();
  delete pStu;
  pStu = nullptr;  //若编译器不支持,则 pStu = NULL;
 
 说明:delete之后最好重置为空,可防止在删除对象后意外使用

 

  • 使用智能指针(强烈推荐)
  shared_ptr<CStudent> ptrStu(new CStudent());
  ptrStu->setAge(14);
  cout<<"Age is :" << ptrStu->getAge();
 

  说明:使用智能指针后,就不用手动释放内存,内存会自动释放。

 
 
 
 
 

 

     

 

posted @ 2013-01-30 08:46  卧野观云  阅读(186)  评论(0)    收藏  举报