设有类定义如下:
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
int SetString(char *src); //设置字符串,在考虑了src的长度后设置当前对象,m_length>=src的长度+1
friend ostream& operator<<(ostream& Out, const CString& S); //输出字符串
};
请编写程序实现如下功能:
为其中的每个成员函数给出实现代码;
重载下标运算符[],使得可以通过[]访问数组的指定元素;
自行根据需要决定是否需要添加拷贝构造函数和析构函数;
main 函数要求如下,不允许修改:
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;
}
/*=======================================================
*学号:
*作业:E15
*功能:请编写程序实现如下功能:
(1)为其中的每个成员函数给出实现代码;
(2)重载下标运算符[],使得可以通过[]访问数组的指定元素;
(3)自行根据需要决定是否需要添加拷贝构造函数和析构函数;
*作者:
*日期:2016.5.15
*========================================================*/
#include<iostream>
using namespace std;
class CString
{
char *m_buff; //指向字符串的指针
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& t); //拷贝构造函数
~CString(); //析构函数
int SetString(char *src); //设置字符串,在考虑了src的长度后设置当前对象,m_length>=src的长度+1
friend ostream& operator<<(ostream& Out,const CString& S); //输出字符串
char operator[](int i)const
{
return m_buff[i];
}
};
CString::CString() //构造函数1,设置为空字符串,m_length=100
{
m_length=100;
m_buff=new char[m_length];
m_buff[0]='\0';
}
CString::CString(char *src) //构造函数2,在考虑了src的长度后初始化当前对象,m_length>=src的长度+1
{
m_length=strlen(src)+1;
m_buff=new char[m_length];
if(m_buff==NULL)
{
cout<<"m_length存储空间分配失败!"<<endl;
exit(0);
}
strcpy(m_buff,src);
}
CString::CString(char ch) //构造函数3,0号元素赋值为ch, m_length=100
{
m_length=100;
m_buff=new char[m_length];
m_buff[0]=ch;
m_buff[1]='\0';
}
CString::CString(const CString& t) //拷贝构造函数
{
m_length=strlen(t.m_buff)+1;
m_buff=new char[m_length];
strcpy(m_buff,t.m_buff);
}
CString::~CString() //析构函数
{
delete[] m_buff;
}
int CString::SetString(char *src) //设置字符串,在考虑了src的长度后设置当前对象,m_length>=src的长度+1
{
m_length=strlen(src)+1;
m_buff=new char[m_length];
if(m_length==NULL)
{
cout<<"m_length存储空间分配失败!"<<endl;
return -1;
}
else
{
strcpy(m_buff,src);
return 1;
}
}
ostream& operator<<(ostream& Out,const CString& S) //输出字符串
{
return Out<<S.m_buff<<endl;
}
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;
}