001:MyString
很经典的题目,考察深拷贝,运算符重载
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
class MyString {
char* p;
public:
MyString(const char* s) {
if (s) {
p = new char[strlen(s) + 1];
strcpy(p, s);
}
else
p = NULL;
}
~MyString() { if (p) delete[] p; }
MyString(const MyString& s) { // 拷贝构造
if (s.p) {
p = new char[strlen(s.p) + 1];
strcpy(p, s.p);
}
else
p = NULL;
}
void Copy(const char* s) {
if (s == p) return;
delete[] p;
p = new char[strlen(s) + 1];
strcpy(p, s);
}
MyString& operator = (const char* s) {
if (p == s) return *this;
delete[] p;
p = new char[strlen(s) + 1];
strcpy(p, s);
return *this;
}
MyString& operator = (const MyString& s) {
if (p == s.p) return *this;
delete[] p;
p = new char[strlen(s.p) + 1];
strcpy(p, s.p);
return *this;
}
friend ostream& operator<<(o