高手来啊,c++问题
// MyString.h#include <string>
#include <iostream>
using namespace std;
class MyString
{
private:
char *str;
int size;
public:
MyString(void);
MyString(char *s)
{size=strlen(s)+1;str=new char[size];if(str==NULL){cout<<"申请空间失败"<<endl;exit(1);}strcpy(str,s);str[size-1]='\0';};
MyString(const MyString&obj)
{size=obj.size;str=new char[size];if(str==NULL){cout<<"申请空间失败"<<endl;exit(1);}strcpy(str,obj.str);str[size-1]='\0';};
~MyString(void);
MyString operator=(MyString &obj);
MyString operator=(char *s);
MyString operator+(MyString &obj);
MyString operator+(char *s);
friend MyString operator+(char *s,MyString &obj);
void show();
};
//myString.cpp
#include "MyString.h"
#include <iostream>
#include <string>
using namespace std;
MyString::MyString(void)
{
size=1;
str=new char[size];
if(str==NULL)
{cout<<"申请空间失败"<<endl;exit(1);}
str[size-1]='\0';
}
MyString::~MyString(void)
{
delete [] str;
}
//串对象赋值
MyString MyString:: operator =(MyString &obj)
{
delete [] str;
size=obj.size;
str=new char[size];
if(str==NULL)
{cout<<"申请空间失败"<<endl;exit(1);}
strcpy(str,obj.str);
str[size-1]='\0';
}
//字符串赋值
MyString MyString::operator=(char *s)
{
delete [] str;
size=strlen(s)+1;
str=new char[size];
if(str==NULL)
{cout<<"申请空间失败"<<endl;exit(1);}
strcpy(str,s);
str[size-1]='\0';
}
//串对象连接
MyString MyString::operator+(MyString &obj)
{
MyString temp;
delete [] temp.str;
temp.size=obj.size+size-1;
temp.str=new char[temp.size];
if(str==NULL)
{cout<<"申请空间失败"<<endl;exit(1);}
strcpy(temp.str,str);
strcat(temp.str,obj.str);
//temp.str[temp.size-1]='\0';
return temp;
}
void MyString::show()
{
cout<<str<<endl;
}
//字符串连接
MyString MyString::operator+(char *s)
{
MyString temp;
delete temp.str;
temp.size=size+strlen(s);
temp.str=new char[temp.size];
if(str==NULL)
{cout<<"申请空间失败"<<endl;exit(1);}
strcpy(temp.str,str);
strcat(temp.str,s);
temp.str[temp.size-1]='\0';
return temp;
}
//c++串与连接串对象
MyString operator+(char *s,MyString &obj)
{
MyString temp;
delete temp.str;
temp.size=obj.size+strlen(s);
temp.str=new char[temp.size];
if(temp.str==NULL)
{cout<<"申请空间失败"<<endl;exit(1);}
strcpy(temp.str,s);
strcat(temp.str,obj.str);
temp.str[temp.size-1]='\0';
return temp;
}
//main
#include "MyString.h"
#include <iostream>
using namespace std;
void main()
{
MyString s("我们的回忆");
MyString m=s;
m.show();
MyString o=m+",你是否还会记得";
o.show();
m="2012了,"+o;
m.show();
}
为啥MyString o=m;是对的;
而MyString o;
o=m;就错了啊;
我单步调试过,运算没问题,可最后它自动跳到析构函数去了,然后就错误了,求解决
追问:来自手机问问我学到数据结构得串,直接string效率地,功能不全啊