# include<iostream>
# include<stdlib.h>
# include<string.h> using namespace std; class String
{
public:
String(const char *str = NULL);
String(const String &other);
~String();
String & operator =(const String &other);
String & operator +(const String &other);
print(){cout<<m_data<<endl;}
private:
char *m_data; // 用于保存字符串
}; String::String(const char *str)
{
if (NULL == str)
{
m_data = new char[1];
*m_data = '\0';
}
else
{
int length = strlen(str);
m_data = new char[length + 1];
strcpy(m_data, str);
}
} String::String(const String &other)
{
int length = strlen(other.m_data);
m_data = new char[length +1];
strcpy(m_data, other.m_data);
} String::~String()
{
delete []m_data;
} String & String::operator =(const String &other)
{
if (this == &other)
return *this; delete []m_data;
int length = strlen(other.m_data);
m_data = new char[length+1];
strcpy(m_data, other.m_data); return *this;
} String & String::operator +(const String &other)
{
String temp;
strcpy(temp.m_data, this->m_data);
delete []m_data;
this->m_data = new char[strlen(this->m_data)+strlen(other.m_data)+1];
strcpy(this->m_data, temp.m_data);
strcat(this->m_data, other.m_data);
return *this; //这里报错 求解释
} void main()
{
String a = "123456";
a.print();
String b = a;
b.print();
String c= a+b; c.print();
}
# include<stdlib.h>
# include<string.h> using namespace std; class String
{
public:
String(const char *str = NULL);
String(const String &other);
~String();
String & operator =(const String &other);
String & operator +(const String &other);
print(){cout<<m_data<<endl;}
private:
char *m_data; // 用于保存字符串
}; String::String(const char *str)
{
if (NULL == str)
{
m_data = new char[1];
*m_data = '\0';
}
else
{
int length = strlen(str);
m_data = new char[length + 1];
strcpy(m_data, str);
}
} String::String(const String &other)
{
int length = strlen(other.m_data);
m_data = new char[length +1];
strcpy(m_data, other.m_data);
} String::~String()
{
delete []m_data;
} String & String::operator =(const String &other)
{
if (this == &other)
return *this; delete []m_data;
int length = strlen(other.m_data);
m_data = new char[length+1];
strcpy(m_data, other.m_data); return *this;
} String & String::operator +(const String &other)
{
String temp;
strcpy(temp.m_data, this->m_data);
delete []m_data;
this->m_data = new char[strlen(this->m_data)+strlen(other.m_data)+1];
strcpy(this->m_data, temp.m_data);
strcat(this->m_data, other.m_data);
return *this; //这里报错 求解释
} void main()
{
String a = "123456";
a.print();
String b = a;
b.print();
String c= a+b; c.print();
}