总时间限制: 1000ms
内存限制: 65536kB
#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; }
// 在此处补充你的代码
};
int main()
{
char w1[200],w2[100];
while( cin >> w1 >> w2) {
MyString s1(w1),s2 = s1;//有复制构造函数,为了严谨,我们要重新写复制构造函数,达到深层复制
MyString s3(NULL);
s3.Copy(w1);//Copy函数我们要自己写
cout << s1 << "," << s2 << "," << s3 << endl;
s2 = w2;//一个char*类型的字符串赋值给了一个类,用到了运算符重载
s3 = s2;//这个不是复制构造函数,这个是赋值操作,也用到了运算符重载
s1 = s3;
cout << s1 << "," << s2 << "," << s3 << endl;//cout无法输出对象,这里也用到了操作符重载
}
}
输入
多组数据,每组一行,是两个不带空格的字符串
输出
对每组数据,先输出一行,打印输入中的第一个字符串三次
然后再输出一行,打印输入中的第二个字符串三次
样例输入
abc def
123 456
样例输出
abc,abc,abc
def,def,def
123,123,123
456,456,456
来源
Guo Wei
针对上面给出代码片段
MyString(const MyString& str) {
if (str.p) {
p = new char[strlen(str.p) + 1];
strcpy(p, str.p);
}
else
p = NULL;
}
MyString& operator=(const char* s) {
if (s) {
this->p = new char[strlen(s) + 1];
strcpy(p, s);
}
else p = NULL;
return *this;
}
MyString& operator=(const MyString& str) {
if (str.p) {
this->p = new char[strlen(str.p) + 1];
strcpy(p, str.p);
}
else p = NULL;
return *this;
}
friend ostream& operator<<(ostream& os, const MyString& str) {
os << str.p;
return os;
}
void Copy(const char* s) {
if (s) {
this->p = new char[strlen(s) + 1];
strcpy(p, s);
}
else p = NULL;
return;
}
~My