#include "CMyString.h"//CMyString.cpp
using namespace std;
CMyString CMyString::operator+(CMyString &obj)
{
cout<<"重载运算符+"<<endl;
char *p=new char[m_length];
for(int k=0;k<m_length;k++)
p[k]=m_p[k];
delete []m_p;
m_p=new char[m_length+obj.m_length];
for(int i=0;i<m_length;i++)
{
m_p[i]=p[i];
//cout<<m_p[i]<<endl;
}
delete []p;
for(int j=m_length;j<m_length+obj.m_length;j++)
{
m_p[j]=obj.m_p[j-m_length];//注意j要减去length
//cout<<m_p[j]<<endl;
}
m_length=m_length+obj.m_length;
//cout<<"m_length="<<m_length;
return *this;
}
void CMyString::operator =(CMyString &obj)
{
cout<<"重载运算符="<<endl;
delete []m_p;
m_length=obj.m_length;
m_p=new char[m_length];
for(int i=0;i<m_length;i++)
m_p[i]=obj.m_p[i];
}
#ifndef _CMYSTRING_H_//CMyString.h
#define _CMYSTRING_H_
#include <iostream>
using namespace std;
class CMyString
{
public:
CMyString(int length,char *p)
{
cout<<"构造string!"<<endl;
m_length=length;
m_p=new char[length];
for(int i=0;i<length;i++)
{
m_p[i]=p[i];
}
//m_p[i]='\0';
}
CMyString(CMyString &obj)//拷贝构造函数没有返回值eg。CPoint(CPoint &obj)
{
cout<<"拷贝构造函数!String"<<endl;
m_length=obj.m_length;
//delete []m_p;
m_p=new char[m_length];
for(int i=0;i<obj.m_length;i++)
m_p[i]=obj.m_p[i];
}
void ShowCMyString()const
{
for(int i=0;i<m_length;i++)
cout<<m_p[i];
cout<<endl;
}
~CMyString()
{
delete []m_p;
cout<<"析构string!"<<endl;
}
int GetLength()
{
return m_length;
}
char* GetP()
{
return m_p;
}
CMyString operator+(CMyString &obj);
void operator =(CMyString &obj);
private:
int m_length;
char *m_p;
};
#endif
#include "CMyString.h"//smain.cpp
#include <string>
using namespace std;
char GetChar()
{
char ch;
while((ch=cin.get())=='\n')
{;}
//cout<<"ch="<<ch<<"!!"<<endl;
return ch;
}
void main()
{
char *p;
cout<<"input the length:";
int length;
cin>>length;
// cin.get();
cout<<"input the string:";
//string b;
//cin>>b;
p=new char[length];
for(int i=0;i<length;i++)
{
p[i]=GetChar();
}
CMyString a(length,p);
a.ShowCMyString();
CMyString b(a);
b.ShowCMyString();
CMyString c(b);
c=a+b;
c.ShowCMyString();
delete []p;
//cout<<length;
}

本文介绍了一个自定义字符串类CMyString的设计与实现,包括构造函数、拷贝构造函数、析构函数及运算符重载等功能。通过实例演示了如何创建字符串对象,并使用重载的加号运算符实现字符串连接。
6107

被折叠的 条评论
为什么被折叠?



