指针与引用的比较

1.初始化要求:引用在创建之初就必须初始化,而指针却没有这个要求 2.可修改性:引用只能进行一次,不能同时引用两个对象,即在初始时候已经决定了引用的对象;指针可以变换指向的对象 3.不存在NULL引用,存在NULL指针 4.测试时候:指针需要经常测试是否为空指针,而引用不需要,故引用的代码效率比较高    

举例说明指针每次都需要测试编写String类的构造,析构,赋值函数 String::String(const char* str) { if(str==NULL) { m_String=new char[1]; *m_String=”; } else { m_String=new char[sizeof(str)+1]; strcpy(m_String,str); } }   String::~String() { if(m_String!=NULL) { delete []m_String; m_String=NULL; } }   String& String::operator=(const String& other) { if(this==&other) return *this; if(m_Sring!=NULL) { delete []m_String; } m_String=new char[strlen(other.m_String)+1]; strcpy(this->m_String,other.m_String); return *this; }

Share and Enjoy:
  • Print this article!
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • LinkedIn
  • Live
  • MySpace
  • RSS
  • Slashdot
  • Technorati
  • TwitThis

Related posts:

  1. Singleton模式
  2. AVL树Source Code
  3. wxWidget 类型转换(wxString, wxdatatime)
  4. CodeBlocks下SDL编译成功实例
  5. 判断链表是否存在环并找出环的入口
  6. STL中的常用的vector,map,set,Sort用法

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word

Contact us

Admin: Bryan Wu