指针与引用的比较
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; }
Related posts:














