设计字符串类CSTRING,包含私有成员数据p(char *p)。根据给定的main函数设计必要的成员函数。int main() { int n,i,j; while(cin>>n) { CSTRING *c=new CSTRING[n+2]; for(i=0;i<n;i++) for(j=0;j<n;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; },输入3 aaa bbb ccc,输出--aaa--bbb--ccc,给出c++代码
时间: 2024-01-21 09:03:02 浏览: 29
下面是设计的CSTRING类的代码:
```cpp
#include <iostream>
#include <cstring>
using namespace std;
class CSTRING {
private:
char *p;
public:
CSTRING() {
p = NULL;
}
CSTRING(const char *str) {
p = new char[strlen(str) + 1];
strcpy(p, str);
}
CSTRING(const CSTRING &str) {
p = new char[strlen(str.p) + 1];
strcpy(p, str.p);
}
~CSTRING() {
if (p != NULL) {
delete[] p;
}
}
bool operator > (const CSTRING &str) const {
return strcmp(p, str.p) > 0;
}
CSTRING& operator += (const CSTRING &str) {
char *temp = new char[strlen(p) + strlen(str.p) + 1];
strcpy(temp, p);
strcat(temp, str.p);
if (p != NULL) {
delete[] p;
}
p = temp;
return *this;
}
friend istream& operator >> (istream &in, CSTRING &str) {
char temp[100];
in >> temp;
str = CSTRING(temp);
return in;
}
friend ostream& operator << (ostream &out, const CSTRING &str) {
out << "--" << str.p << "--";
return out;
}
};
```
在主函数中,先输入n,然后创建一个长度为n+2的CSTRING数组,接着嵌套for循环,对数组进行冒泡排序,最后将每个字符串拼接到最后一个字符串上,并输出。最后别忘了释放内存。
```cpp
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; i++) {
for (j = 0; j < n - i - 1; j++) {
if (c[j] > c[j + 1]) {
swap(c[j], c[j + 1]);
}
}
}
for (i = 0; i < n; i++) {
c[n + 1] += c[i];
}
cout << c[n + 1] << endl;
delete[] c;
}
return 0;
}
```
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)