【问题描述】不允许修改主函数,请将以下代码补充完整。 class String { char *ptr; public: String(char *s) { ptr=new char[strlen(s)+1]; strcpy(ptr, s); } ~String() { delete []ptr; } void print() { cout<<ptr<<endl; } }; int main( ) { String p1("book"), p2("pen"),p3("good"),p4; p4 = p4 = p1 ; p3 = p1 = p2; cout<<"p2:"; p2.print(); cout<<"p1:"<<p1; cout<<"p3:"<<p3; p4+=p3; cout<<"p4:"<<p4; return 0; } 【样例输入】 无 【样例输出】 p2:pen p1:pen p3:pen p4:bookpen
时间: 2024-01-22 12:03:15 浏览: 59
c++中try catch的用法小结
【参考代码】
```
#include <iostream>
#include <cstring>
using namespace std;
class String {
char *ptr;
public:
String(char *s) {
ptr = new char[strlen(s) + 1];
strcpy(ptr, s);
}
~String() {
delete []ptr;
}
void print() {
cout << ptr << endl;
}
String& operator=(const String &s) {
if (this == &s) return *this;
delete []ptr;
ptr = new char[strlen(s.ptr) + 1];
strcpy(ptr, s.ptr);
return *this;
}
String& operator+=(const String &s) {
char *temp = ptr;
ptr = new char[strlen(ptr) + strlen(s.ptr) + 1];
strcpy(ptr, temp);
strcat(ptr, s.ptr);
delete []temp;
return *this;
}
friend ostream& operator<<(ostream &os, const String &s) {
os << s.ptr;
return os;
}
};
int main() {
String p1("book"), p2("pen"), p3("good"), p4;
p4 = p4 = p1;
p3 = p1 = p2;
cout << "p2:";
p2.print();
cout << "p1:" << p1 << endl;
cout << "p3:" << p3 << endl;
p4 += p3;
cout << "p4:" << p4 << endl;
return 0;
}
```
阅读全文