MyString的实现

这里简单实现一个string类,需要注意的点。主要是string类的拷贝构造函数,以及输入重载。

/*
	author:gs<song0071000#126.com>
	time:20140514
	function:implement of string class "MyString"

*/
#include<iostream>
#include<cstring>
using namespace std;

#define MAX_LINE 512

class MyString
{
public:
	MyString(const char* p = NULL)
	{
		cout<<"we malloc memory!"<<endl;
		if(p == NULL)
		{
			ptr = new char[1];
			ptr[0]='\0';
		}
		else
		{
			ptr = new char[strlen(p)+1];
			strcpy(ptr,p);
		}
	}

	~MyString()
	{
		cout<<"we free memory!"<<endl;
		delete [] ptr;
	}

	MyString(const MyString& str)
	{
		ptr = new char[strlen(str.ptr)+1];
		strcpy(ptr,str.ptr);
	}

	MyString& operator=(const MyString& str)
	{
		if(&str == this)//最好使用地址进行比较 不要使用str == *this这种方式
			return *this;
		delete [] ptr;
		ptr = new char[strlen(str.ptr)+1];
		strcpy(ptr,str.ptr);
		return *this;
	}

	friend ostream& operator<<(ostream &os,const MyString &c)
	{
		os<<c.ptr;
		return os;
	}


	friend istream& operator>>(istream &is,MyString &c)//这个自定义的string输入始终是个问题
	{
		char temp[MAX_LINE];
		is.get(temp,MAX_LINE);//istream中get函数的妙处就是它不会将\n读取并存入到temp中,若输入超过了MAX_LINE那么,实际只会读入前MAX_LINE-1个字符,第MAX_LINE个空间放入'\0'
		if(is)
			c=temp;//这里隐式类型转换,先以temp为参数生成一个MyString的临时实例对象,然后调用operator将其赋值给c
		return is;
	}

private:
	char* ptr;
};

int main()
{
	MyString a;
	MyString b("1234");
	cout<<a<<endl;
	cout<<b<<endl;
	MyString c("456789");
	cout<<c<<endl;
	MyString d;
	cin>>d;
	cout<<d<<endl;
	return 0;
}

你可能感兴趣的:(C++,MyString,string的拷贝构造函数,string的输入重载)