现在的位置: 首页 > 综合 > 正文

C++自实现string

2013年08月05日 ⁄ 综合 ⁄ 共 1231字 ⁄ 字号 评论关闭
要求自实现string的基本函数,构造函数,析构函数等,缘分呐,不得不认真对待一下,回来仔细查了下,总结一下:C++实现的代码

#include<iostream.h>
class string{
public:
string(const char*str=NULL);//注意指针常量和常量指针的区别,const在前表示是常量(指针)而不

//是指针常量
string(const string&other);
~string();
string&operator=(const string & other);
void print()
{
cout<<m_data<<endl;
}
private:
char*m_data;
};
string::string(const char*str){//注意在类外实现成员函数时的表达方式
const char*p=str;//只能用一个常量指针变量来指向常量指针变量,而不能用一般的指针变量来指向一个常量指针
while(*p!='\0')p++;
m_data=new char[p-str+1];//在开辟存储空间时,原则上也可以用一个char*指针指向字符串(数组),但这样做是很危险的,因为字符指针可能会指向不可知的位置,所以我们在为m_data申请空间的时候是以数组的方式申请而不是用new char,注意要为串结束符\0申请空间。
//m_data=new char;
char*q=m_data;
while(*str){*q++=*str++;}
*q='\0';//一定要记得加串结束符
}
string::string(const string&other){
char*q=other.m_data;
while(*q++);
m_data=new char[q-other.m_data+1];
char*p=m_data;
char*r=other.m_data;//

while(*p++=*r++);

}
string::~string(){
if(m_data)
delete[] m_data;//释放字符数组
}
string& string::operator=(const string&other)
{

//拷贝构造函数在返回时需要返回一个有效的引用,不能返回对一个局部变量的引用
if(m_data) delete[] m_data;//先释放掉以前的内存
if(other.m_data)
{
char*q=other.m_data;
while(*q++);
m_data=new char[q-other.m_data+1];
char*p=m_data;
char*r=other.m_data;//

while(*p++=*r++);

}
else m_data=NULL;
return *this;//返回当前对象
}
void main()
{
string s("dhhh");
s.print();
string s1(s);
s1.print();
string s2=s;
s2.print();
return;
}

抱歉!评论已关闭.