自定义的string类出错
对 = 和 + 重载时;
class MyString
{
private:
int len;
char* c_MyString;
public:
MyString(int n);
~MyString();
void Getchar();
void Showstring();
bool operator == (const MyString &string);
bool operator != (const MyString &string);
bool operator > (const MyString &string);
bool operator < (const MyString &string);
MyString &operator + (const MyString &string);
MyString &operator = (const MyString &string);
char& operator [] (int n);
};
MyString &MyString::operator + (const MyString &string)
{
MyString a_MyString(100);
int i, n = len + string.len;
a_MyString.len = len + string.len;
char* ptr = a_MyString.c_MyString;
char* ptr1 = string.c_MyString;
char* ptr2 = c_MyString;
for(i = 1; i <= n; i ++)
{
if(i > len)
*ptr++ = *ptr2++;
else
*ptr++ = *ptr1++;
}
return a_MyString;
}
MyString &MyString::operator = (const MyString &string)
{
int n = string.len;
len = n;
delete [] c_MyString;
char* ptr = c_MyString;
char* ptr1 = string.c_MyString;
while(n--)
*ptr++ = *ptr1++;
return *this;
}
执行 s1 = s2 + s3 时出错,高手指点。
[解决办法]
class MyString{ size_t m_len;public: char* m_data;public: MyString(const char* otherChar = NULL); MyString(const string& other); MyString(const MyString& other); ~MyString();public: MyString& operator =(const MyString& other); friend MyString operator +(const MyString& str1, const MyString& str2);};//默认参数可作无参数构造函数使用MyString::MyString(const char* otherChar): m_len(strlen(otherChar)), m_data(new char[m_len + 1]){ if (otherChar == NULL) { *m_data = '\0'; } else { for (size_t i=0; i<m_len+1; ++i) { m_data[i] = otherChar[i]; } }}//我们的这个 string 类要支持 string 对象MyString::MyString(const string& other): m_len(other.size()), m_data(new char[m_len + 1]){ if (other.size() == 0) { *m_data = '\0'; } else { for (size_t i=0; i<m_len+1; ++i) { m_data[i] = other.c_str()[i]; } }}//拷贝构造函数MyString::MyString(const MyString& other): m_len(other.m_len), m_data(new char[other.m_len + 1]){ if (other.m_len == 0) { *m_data = '\0'; } else { for (size_t i=0; i<m_len+1; ++i) { m_data[i] = other.m_data[i]; } }}//敬爱的析构函数,总是扫尾MyString::~MyString(){ delete[] m_data;}//赋值操作符重载MyString& MyString::operator =(const MyString &other){ //自赋值检测 if (this == &other) { return *this; } //只有源对象和目标对象的长度不等时才重新分配空间 if (m_len != other.m_len) { m_len = other.m_len; delete[] m_data; m_data = new char[m_len + 1]; } for (size_t i=0; i<m_len; ++i) { m_data[i] = other.m_data[i]; } return *this;}//字符串相加,外部友元函数MyString operator +(const MyString& str1, const MyString& str2){ char* temp = new char[str1.m_len + str2.m_len + 1]; //忽略掉str1末尾的'\0' for (size_t i=0; i<str1.m_len; ++i) { temp[i] = str1.m_data[i]; } for (size_t j=0; j<str2.m_len+1; ++j) { temp[str1.m_len+j+1] = str2.m_data[j]; } //return MyString(temp) //这样不行,temp 的资源未释放掉 //没办法,新建立一个临时对象把 temp 的资源传递给它 MyString strTemp(temp); //然后释放掉 temp 的资源 delete[] temp; //对象 strTemp 的生命期到这里结束,会自动调用析构函数释放掉堆空间,不用担心内存泄漏啦 return strTemp;}