修改以下代码# include <iostream> # include <string.h> using namespace std; class cstring{ char *ps; int n; public: cstring(){ n=0; ps=0;} cstring(char *cp) { n= strlen(cp)+1; ps= new char[ n]; strcpy(ps,cp);} ~ cstring(){delete [ ]ps; } cstring & operator= ( char *p) {delete []ps; n= strlen(p)+ 1; ps = new char[n]; strcpy(ps,p); return *this; } cstring & operator= ( cstring &s) {delete []ps; n=s.n; ps= new char[n]; strcpy(ps,s. ps); return *this;} cstring & operator + (char *p) {char *p1;int n1=n; p1= new char[n1]; strcpy(p1,ps); n+=strlen(p)+ 1; delete []ps; ps= new char[ n]; strcpy(ps, p1); delete []p1; strcat(ps,p); return *this;}; cstring & operator + ( cstring &s) {char *p1;int n1=n; p1 = new char[n1]; strcpy(p1 ,ps); n+=s.n; delete []ps; ps = new char[ n]; strcpy( ps,p1); delete []p1; strcat(ps,s.ps); return *this; } void disp(){ cout<< ps<<endl;} }; int main( ) {cstring str1 ,str2, str3(" string class "),str4; char *pc=" test"; cout< "pc="<< pc << endl; str1= pc; cout<<"str1="; str1. disp( ); str2=str3; cout<< "str2= "; str2. disp( ); cout << "tr3="; str3. disp(); str4=str3+pc; cout<< "str3+pc="; str4. disp(); str4=str1+str2;cout<<"str1+str2=";str4.disp(); }
时间: 2023-06-14 17:07:59 浏览: 101
修改后的代码如下:
#include <iostream>
#include <cstring>
using namespace std;
class cstring{
char *ps;
int n;
public:
cstring(){
n = 0;
ps = nullptr;
}
cstring(char *cp){
n = strlen(cp) + 1;
ps = new char[n];
strcpy(ps, cp);
}
~cstring(){
delete[] ps;
}
cstring &operator=(char *p){
delete[] ps;
n = strlen(p) + 1;
ps = new char[n];
strcpy(ps, p);
return *this;
}
cstring &operator=(cstring &s){
delete[] ps;
n = s.n;
ps = new char[n];
strcpy(ps, s.ps);
return *this;
}
cstring operator+(char *p){
cstring temp;
temp.n = n + strlen(p) + 1;
temp.ps = new char[temp.n];
strcpy(temp.ps, ps);
strcat(temp.ps, p);
return temp;
}
cstring operator+(cstring &s){
cstring temp;
temp.n = n + s.n;
temp.ps = new char[temp.n];
strcpy(temp.ps, ps);
strcat(temp.ps, s.ps);
return temp;
}
void disp(){
cout << ps << endl;
}
};
int main(){
cstring str1, str2, str3("string class"), str4;
char *pc = "test";
cout << "pc=" << pc << endl;
str1 = pc;
cout << "str1=";
str1.disp();
str2 = str3;
cout << "str2=";
str2.disp();
cout << "str3=";
str3.disp();
str4 = str3 + pc;
cout << "str3+pc=";
str4.disp();
str4 = str1 + str2;
cout << "str1+str2=";
str4.disp();
return 0;
}
阅读全文