发布网友 发布时间:2024-10-20 13:51
共1个回答
热心网友 时间:2024-12-01 06:51
#include<iostream>using std::cin;using std::cout;using std::endl;using std::string;class CString{ char * m_pbuff; //指向字符串的指针 int m_length; //表示当前字符串的最大允许长度,也就是字符数组的长度public: CString(); //构造函数1,设置为空字符串,m_length=100 CString(char *src); //构造函数2,在考虑了src的长度后初始化当前对象, m_length>=src的长度+1 CString(char ch); //构造函数3,0号元素赋值为ch, m_length=100 CString(const CString&s); ~CString();//析构函数 int setString(char *src); //设置字符串,在考虑了src的长度后设置当前对象,m_length>=src的长度+1 char &operator[](int n)const;//重载[] friend ostream& operator<<(ostream& Out, const CString& S); //输出字符串};CString::CString(){ m_pbuff=new char[100]; m_length=100; m_pbuff[0]='\0';//空字符串}CString::CString(char *src){ m_length=0; while(src[m_length]!='\0')//统计src的字符个数 { m_length++; } m_length+=1; m_pbuff=new char[m_length]; for(int i=0;i<m_length;i++) { m_pbuff[i]=src[i]; }}CString::CString(char ch){ m_pbuff=new char[100]; m_length=100; m_pbuff[0]=ch; m_pbuff[1]='\0';//空字符串}CString::CString(const CString&s){ m_length=s.m_length; m_pbuff=new char[m_length]; int i=0; while(s.m_pbuff[i]!='\0') { m_pbuff[i]=s.m_pbuff[i]; i++; } m_pbuff[i]='\0';}CString::~CString(){ delete[] m_pbuff;//释放内存}int CString::setString(char *src){ delete[] m_pbuff;//释放原内存 m_length=0; while(src[m_length]!='\0')//统计src的字符个数 { m_length++; } m_length+=1; m_pbuff=new char[m_length]; for(int i=0;i<m_length;i++) { m_pbuff[i]=src[i]; } return m_length;}char &CString::operator[](int n)const{ return m_pbuff[n];}ostream& operator<<(ostream& Out, const CString& S){ for(int i=0;S[i]!='\0';i++) { Out<<S[i]; } Out<<endl; return Out;}void main(){ CString s1; cout<<s1; s1.setString("abc1"); cout<<s1; CString s2("abc2"); cout<<s2; CString s3('a'); cout<<s3; CString s4(s2); cout<<s4;}添加一个析构函数,一个copy函数,一个[]重载函数,如有问题可以继续问