调用AddString时,有时正常运行有时太窗提示停止工作,亲大家帮我看看是哪里的错误
代码如下:
MyString.h
C/C++ code
#ifndef MYSTRING_H_INCLUDED
#define MYSTRING_H_INCLUDED
#include <iostream>
using namespace std;
class MyString
{
public:
MyString(const char* str = NULL);
~MyString();
MyString& AddMyString(MyString&);
MyString& operator= (const char *str);
MyString& operator= (const MyString);
friend ostream & operator<< (ostream &, const MyString &);
private:
char *default_str;
size_t str_len;
};
#endif
// MYSTRING_H_INCLUDED
MyString.cpp
C/C++ code
#include <cstring>
#include "MyString.h"
#include <iostream>
using namespace std;
MyString::MyString(const char *str) /* str==NULL */
{
if(str == NULL)
{
str_len = 0;
default_str = new char[1];
*default_str = '\0';
}
else
{
str_len = strlen(str);
default_str = new char[1 + str_len]; /* 加1存放'\0' */
strcpy(default_str, str);
}
}
ostream& operator << (ostream &os, const MyString &str) /*重载<<, 友元函数*/
{
os << str.default_str;
return os;
}
MyString::~MyString()
{
if(NULL != default_str)
{
delete [] default_str;
}
}
MyString& MyString::AddMyString(MyString& str_obj) /*字符串相加*/
{
strcat(default_str, str_obj.default_str);
str_len = strlen(default_str);
return *this;
}
main.cpp
C/C++ code
#include <iostream>
#include "MyString.h"
using namespace std;
int main()
{
MyString str1("hello");
MyString str2("world");
//MyString str2 = "world";
cout << "str1=" << str1 << ",str2=" << str2 << endl;
cout << "str1+str2=" << str1.AddMyString(str2) << endl;
return 0;
}
还有就是,返回类型为MyString和MyString&在这里有什么区别呢,thanks
子衿沉夜