#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;
}