014:MyString

1、右边赋值字符串类型要进行重载,右边赋值是同类时要深拷贝。
2、同时,复制构造函数需要重载,深拷贝。
3、友元函数可以在类里面定义,是全局函数。
(赋值重载时,忘记写返回值return (*this),本地是对的,但是提交会报错,不知道啥原因)
参考:014 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; }
	
	MyString(MyString &S)
	{
		if (S.p)
		{
			p = new char[strlen(S.p) + 1];
			strcpy(p, S.p);			
		}
		else
			p = NULL;
	}
	
	void Copy(const char * s)
	{
		if (p) delete [] p; 
		
		p = new char[strlen(s) + 1];
		strcpy(p, s);
	}
	
	MyString & operator = (const char * s)
	{
		if (s)
		{
			delete [] p;
			p = new char[strlen(s) + 1];
			strcpy(p, s);
		}
		else p = NULL;
		
		return (*this);
	}
	
	MyString & operator = (MyString &S)
	{
		if (S.p)
		{
			delete [] p;
			p = new char[strlen(S.p) + 1];
			strcpy(p, S.p);
		}
		else p = NULL;
		
		return (*this);
	}
	
	friend ostream & operator<<(ostream & a, MyString &S)
	{
		cout << S.p;
		return a;
	}
};
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;
		
	}
}
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值