001:MyString
描述
补足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; }
// 在此处补充你的代码
};
int main()
{
char w1[200],w2[100];
while( cin >> w1 >> w2) {
MyString s1(w1),s2 = s1;
MyString s3(NULL);
s3.Copy(w1);
cout << s1 << "," << s2 << "," << s3 << endl;
s2 = w2;
s3 = s2;
s1 = s3;
cout << s1 << "," << s2 << "," << s3 << endl;
}
}
输入
多组数据,每组一行,是两个不带空格的字符串
输出
对每组数据,先输出一行,打印输入中的第一个字符串三次
然后再输出一行,打印输入中的第二个字符串三次
样例输入
abc def
123 456
样例输出
abc,abc,abc
def,def,def
123,123,123
456,456,456
分析输出,得出需要补充的函数有哪些
#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]; //动态数组——长度+1
strcpy(p,s); //复制
}
else
p = NULL; //为空则空
}
~MyString() { if(p) delete [] p; } //析构函数——删除动态数组
// 在此处补充你的代码
MyString & Copy(char *s){ //copy函数,用于将列表copy至mystring
p = new char[strlen(s) + 1];
strcpy(p,s);
}
MyString(const MyString &C){ //复制函数,用于复制同类型
p = new char[strlen(C.p) + 1];
strcpy(p,C.p);
}
MyString& operator = (const char *C){ //赋值函数,将列表赋值给MyString
p = new char[strlen(C) + 1];
strcpy(p,C);
return *this; //返回完成赋值后的当前对象
}
MyString & operator =(const MyString&s){ //赋值函数,用于赋值相同类型
if (p==s.p){ //若完全相同,就不用赋值,直接返回当前对象
return *this;
}
p = new char[strlen(s.p) + 1];
strcpy(p,s.p);
return *this; //返回当前对象,且为引用类型——可以改变
}
friend ostream& operator << (ostream& o, const MyString& s){
o<<s.p;
return o;
}
//友元osream,让os可以访问自己的p元素,
//需要一个复制函数——返回MyString &
//需要一个=重载,得到MyString
//=重载,得到列表指针
//需要一个Copy函数,实参为指针列表
//需要一个强制转换函数——输出s
};
int main()
{
char w1[200],w2[100];
while( cin >> w1 >> w2) { //输入 abc def 123 456
MyString s1(w1),s2 = s1; //w1复制给s1, s1赋值给s2,
//MyString 复制函数返回MyString &
//MyString 重载=,返回MyString &
MyString s3(NULL);
//MyString 构造函数可以Null
s3.Copy(w1);
//MyString Copy函数(实参为列表指针)
cout << s1 << "," << s2 << "," << s3 << endl;
//cout没法重载,把s1强制转换成char
s2 = w2; //MyString 重载=,得到列表指针
s3 = s2; //MyString 重载=,得到MyString
s1 = s3; //同上
cout << s1 << "," << s2 << "," << s3 << endl;
}
}