俗话说的好:自闭从不单行,永远双至。果然这一场又自闭了。C语言没学好。。。。
Problem A: 字符串类(I)
main 函数:
int main() { STR e; STR h("Hello World!"); char s[100001]; cout << e.length() << " "; e.putline(); cout << h.length() << " "; h.putline(); while(gets(s) != NULL) { STR str(s); cout << str.length() << " "; str.putline(); } }
怎么说那,本来以为RE到绝望了。。。。。,没想到还有B题。
总体来说还是水题,怎么说的怎么写吧。
AC代码:
#include <bits/stdc++.h> using namespace std; class STR { char *p; int len; public: STR():p(NULL),len(0){}; STR(const char *s){len = strlen(s);p = new char[len+1];strcpy(p,s);}; int length() { return len; } void putline() { if(p==NULL) cout << endl; else cout << p << endl; } ~STR() { len = 0; if(p!=NULL) delete []p; } }; int main() { STR e; STR h("Hello World!"); char s[100001]; cout << e.length() << " "; e.putline(); cout << h.length() << " "; h.putline(); while(gets(s) != NULL) { STR str(s); cout << str.length() << " "; str.putline(); } }
Problem B: 字符串类(II)
main 函数:
int main() { STR e; STR h("Hello World!"); STR he = e + h; cout << he.length() << " "; he.putline(); cout << e.length() << " "; e.putline(); cout << h.length() << " "; h.putline(); e += h; cout << e.length() << " "; e.putline(); cout << h.length() << " "; h.putline(); char s1[100001], s2[100001]; while(gets(s1) != NULL && gets(s2) != NULL) { STR str1(s1), str2(s2); STR str = str1 + str2; cout << str.length() << " "; str.putline(); cout << str1.length() << " "; str1.putline(); cout << str2.length() << " "; str2.putline(); str2 += str1; cout << str2.length() << " "; str2.putline(); cout << str1.length() << " "; str1.putline(); } }
这个题RE到自闭,分析原因应该是忘记老师之前讲过的指针悬空问题,对于+=函数没有返回引用,也没有写拷贝构造函数,导致指针悬空,在析构的时候发生了错误。
附博客(讲返回对象与引用区别的):
https://www.cnblogs.com/JMLiu/p/7928425.html
AC代码1(不返回引用):
#include <bits/stdc++.h> using namespace std; class STR { char *p; int len; //static int num; public: STR():p(NULL),len(0){}; STR(const char *s){len = strlen(s);p = new char[len+1];strcpy(p,s); p[len] = '