014: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;
}
}
思路
MyString s1(w1)
需要构造函数
MyString s2=s1
需要复制构造函数
s3.Copy(w1)
调用了
C
o
p
y
Copy
Copy函数
s2=w1
需要构造函数s2=t(w1)
s1=s3;
重载
=
=
=
在重载 = = =时, p = = x . p p==x.p p==x.p是为了防止出现 s 1 = s 1 s1=s1 s1=s1的调用导致两个是一样的还调用了 = = =
#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& x) {
if (x.p) {
p = new char[strlen(x.p + 1)];
strcpy(p, x.p);
}
else
p = NULL;
}
MyString() {
}
void Copy(const char* str) {
if (str) {
p = new char[strlen(str) + 1];
strcpy(p, str);
}
else p = NULL;
}
MyString& operator =(const MyString& x) {
if (p == x.p) return *this;
if (p)delete[]p;
if (x.p) {
p = new char[strlen(x.p) + 1];
strcpy(p, x.p);
}
else p = NULL;
return *this;
}
friend ostream& operator <<(ostream& os, const MyString& x) {
os << x.p;
return os;
}
};
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;
}
}