014:MyString

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;

	}
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值