调用AddString时,有时正常运行有时太窗提示停止工作,亲大家帮我看看是哪里的错误代码如下:MyString.hC/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_INCLUDEDMyString.cppC/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.cppC/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
1 回答
子衿沉夜
TA贡献1828条经验 获得超3个赞
strcat(default_str, str_obj.default_str);
default_str要有足够的空间存储相加之后的字符串
建议新开辟一块内存,把以前的那个free掉
返回类型为引用类型的话,可以作为左值
- 1 回答
- 0 关注
- 416 浏览
添加回答
举报
0/150
提交
取消