**
1461: 重载(15)–string类
**
Description
设计字符串类CSTRING,包含私有成员数据p(char *p)。根据给定的main函数设计必要的成员函数。main函数已给定,提交时只需要提交main函数外的代码部分。
int main()
{
int n,i,j;
while(cin>>n)
{
CSTRING *c=new CSTRING[n+2];
for(i=0;i<n;i++)
{
cin>>c[i];
}
for(i=0;i<n-1;i++)
for(j=0;j<n-i-1;j++)
if(c[j]>c[j+1])
{
c[n]=c[j];
c[j]=c[j+1];
c[j+1]=c[n];
}
for(i=0;i<n;i++)
c[n+1]+=c[i];
cout<<c[n+1]<<endl;
delete[] c;
}
return 0;
}
Input
包含多组数据(数据均正确合法)
每组数据包含2行,第1行为1个正整数n,表示字符串的个数n;第2行包含有n个字符串,用空格隔开。
Output
对于每组测试数据需要输出n个字符串按照升序排序以后的结果,具体格式详见Sample Output。
Sample Input
3
aaa ccc bbb
5
ccccc bbbbbb aaaaa ddddd rrrrr
Sample Output
–aaa–bbb–ccc
–aaaaa–bbbbbb–ccccc–ddddd–rrrrr
我的答案
#include<iostream>
#include<string.h>
using namespace std;
class CSTRING {
private:
char* p;
public:
CSTRING() {
int len = 0;
p = new char[len + 1];
p[0] = '\0';
}
CSTRING(const char* c) {
int len = strlen(c);
p = new char[len + 1];
strcpy(p, c);
}
CSTRING(const CSTRING& c) {
int len = strlen(c.p);
p = new char[len + 1];
strcpy(p, c.p);
}
CSTRING operator+=( CSTRING& s) {
char* str = new char[strlen(p) + strlen(s.p) + 3];
str[0] = '\0';
strcat(str, p);
strcat(str, "--"); strcat(str, s.p);
delete[]p;
p = str;
return *this;
}
friend ostream& operator<<(ostream& out, CSTRING& d);
friend istream& operator>>(istream& in, CSTRING& d);
int operator>(const CSTRING& c);
};
ostream& operator<<(ostream& out, CSTRING& d) {
out << d.p;
return out;
}
istream& operator>>(istream& in, CSTRING& d) {
in >> d.p;
return in;
}
int CSTRING:: operator>(const CSTRING& c) {
if (strcmp(p, c.p)>0){
return 1;
}else {return 0;
}
}