运算符重载之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; }
// 在此处补充你的代码
	//需要重载<<运算符
	friend ostream & operator<<(ostream &os,const MyString mystr)
	{
		for(int i=0;i<strlen(mystr.p);i++)
		{
			os<<mystr.p[i];
		}
		return os;
	}

	//对象之间赋值,需调用拷贝构造函数
	MyString(const MyString &s)
	{
		if( s.p) {
			p = new char[strlen(s.p) + 1];
			strcpy(p,s.p);
		}
		else
			p = NULL;
	}

	//定义拷贝函数
	MyString Copy(const MyString &s)
	{
		if( s.p) {
			p = new char[strlen(s.p) + 1];
			strcpy(p,s.p);
		}
		else
			p = NULL;

		return *this;
	}

	//重载=运算符,这里没想通形参不应该是const char*s吗
	MyString operator =(const MyString &s)
	{
		if( s.p) {
			p = new char[strlen(s.p) + 1];
			strcpy(p,s.p);
		}
		else
			p = NULL;

		return *this;
	}
	//
};
int main()
{
	char w1[200],w2[100];
	while( cin >> w1 >> w2) {
		MyString s1(w1);
		MyString s2 = s1;
		MyString s3(NULL);
		s3.Copy(w1);
		cout << s1 << "," << s2 << "," << s3 << endl;

		s2 = w2;
		s3 = s2;
		s1 = s3;
		cout << s1 << "," << s2 << "," << s3 << endl;
	}
	return 0;
}

 

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页