Description
封装一个字符串类,用于存储字符串和处理的相关功能,支持以下操作:
- STR::STR()构造方法:创建一个空的字符串对象。
- STR::STR(const char *)构造方法:创建一个字符串对象,串的内容由参数给出。
- STR::length()方法:返回字符串的长度。
- STR::putline()方法:输出串的内容,并换行。
- 运算符“+”和“+=”,表示两个字符串的连接运算,规则为:
c = a + b 表示串c中的字符是a和b的连接:“a+b”的结果是一个新的字符串,串a和串b的内容不变。
a += b 表示串a中的字符是a和b的连接:串b中的内容不变
你设计一个字符串类STR,使得main()函数能够正确运行。
append.cc中已给出main()函数。
Invalid Word(禁用单词)错误:“string”、“vector”等被禁用。
Input
输入有若干行,每行一个字符串。
Output
每组测试数据对应输出一行,包含两部分内容,首先是一个整数,表示输入串的长度,然后是输入的字符串,两者用一个空格分开。格式见sample。
Sample Input
A
123456789
Sample Output
12 Hello World!
0
12 Hello World!
12 Hello World!
12 Hello World!
10 A123456789
1 A
9 123456789
10 123456789A
1 A
HINT
AC代码
#include <bits/stdc++.h>//对于NULL的使用认识不清
using namespace std;
class STR
{
char *s;
int len;
friend STR &operator+=(STR &t1, STR &t2);
public:
STR()
{
// s=new char [1];
// s[0]='\0';//这样做也可以
// len=0;
s=NULL;//一个Null能不能使用strcpy
len=0;
}
STR( char *aa)
{
s=new char[strlen(aa)+1];
strcpy(s,aa);
len=strlen(s);
}
STR(const STR &t1)
{
s=new char[strlen(t1.s)+1];
strcpy(s,t1.s);
len=strlen(s);
}
int length()
{
return len;
}
void putline()
{
if(s!=NULL)
cout<<s<<endl;
else
cout<<endl;
}
STR operator+(STR &t2)
{
STR temp;
if(s!=NULL)
{temp.s=new char[strlen(s)+strlen(t2.s)+1];
temp.len=len+strlen(t2.s);
strcpy(temp.s,s);
strcat(temp.s,t2.s);
return temp;}
else
return t2;
}
~STR()
{
if(s!=NULL)
delete []s;
}
};
STR &operator+=(STR &t1, STR &t2)
{
char *k;
if(t1.s!=NULL)//必须要对NULL和非NULL分别研究
{k=new char [strlen(t1.s)+strlen(t2.s)+1];
strcpy(k,t1.s);
delete []t1.s;
t1.s=new char [strlen(k)+strlen(t2.s)+1];
strcpy(t1.s,k);
strcat(t1.s,t2.s);
t1.len=strlen(k)+strlen(t2.s);
delete []k;
}
else
{
t1.s=new char [strlen(t2.s)+1];
strcpy(t1.s,t2.s);
t1.len=strlen(t2.s);
}
return t1;
}
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();
}
}
1.在解答此题时总是出现能编译但不能运行的问题,原因在于未对NULL指针进行处理
NULL指针即由零转换而来的指针是无效的指针。换句话说当我们将零赋值给一个指针变量时,绝对不能企图使用该指针所指向的内存中存储的内容,本例中当我们使用库函数strcpy,和strcat,以及对其的输出操作时,查看了其指针参数所指向的内容,所以产生错误
2.NULL的使用,NULL只能用于比较或赋值运算,其他地方用NULL,均为非法;
Ps为啥错误用NULL程序会中止执行呢
这是因为C语言对内存位置0强加了硬保护,当错误使用NULL时立即停止执行