描述
补足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
我写的时候一直RE,然后我从oj上把那组数据下载下来了,我的程序的输出明明和oj上的数据是一模一样的。但是交上去就是RE,后来找了很久的原因,原来是我没有重载MyString & operator=(const MyString &ms) 这个函数。
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
class MyString {
char * p;
public:
MyString(const char * s) {
// printf("initial \n");
if( s) {
p = new char[strlen(s) + 1];
strcpy(p,s);
}
else
p = NULL;
}
~MyString() { if(p) delete [] p; }
// 在此处补充你的代码
MyString(const MyString &str){
// printf("copy constructor\n");
if(this==&str) return ;
if(str.p){
p=new char[strlen(str.p)+1];
strcpy(p,str.p);
}
else{
if(p) delete [] p;
p=NULL;
}
}
MyString & operator=(const char *str){
// printf("overload = const char *\n");
if(p) delete [] p;
if(str){
p=new char[strlen(str)+1];
strcpy(p,str);
}else{
p=NULL;
}
return *this;
}
MyString & operator=(const MyString &ms){
// printf("operator = MyString\n");
if(this==&ms) return *this;
if(p) delete [] p;
p=new char[strlen(ms.p)+1];
strcpy(p,ms.p);
return *this;
}
MyString& Copy(const char *str){
// printf("copy()\n");
if(p) delete [] p;
if(str){
p=new char[strlen(str)+1];
strcpy(p,str);
}else{
p=NULL;
}
return *this;
}
friend ostream & operator<<(ostream &os,const MyString &str){
// printf("overload << \n");
os<<str.p;
return os;
}
};
int main()
{
freopen("C:\\Users\\Ambition\\Desktop\\in.txt","r",stdin);
// freopen("C:\\Users\\Ambition\\Desktop\\out.txt","w",stdout);
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;
}
}

被折叠的 条评论
为什么被折叠?



