码迷,mamicode.com
首页 > 其他好文 > 详细

string实现

时间:2014-10-07 17:17:53      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:blog   os   ar   for   2014   c   on   log   r   

class my_string{
	friend ostream& operator<< (ostream&,my_string&);
public:
	my_string():data(NULL)
	{
	}
    my_string(const char* str)
	{
		int n = strlen(str);
		data = new char[n+1];
		strcpy(data,str);
	}
    my_string(const my_string &other):data(NULL)
	{
		*this = other;
	}
    my_string& operator=( const my_string& other)
	{
		if(this == &other)
			return *this;
		delete []data;
		int n = other.size();
		data = new char[n+1];
		strcpy(data,other.data);
		return *this;
	}
    my_string operator+(const my_string& other)const
	{
		int n = strlen(data);
		int m = strlen(other.data);
		my_string newstr;
		newstr.data = new char[m+n+1];
		for(int i = 0; i < n; i++)
			newstr[i] = data[i];
		for(int i = n; i < n+m; i++)
			newstr[i] = other.data[i-n];
		newstr[m+n] = NULL;
		return newstr;
	}
    bool operator==(const my_string& other)
	{
		return !strcmp(data,other.data);
	}
    char& operator[](int pos)
	{
		assert(pos < size());
		return data[pos];
	}
    int size()const
	{
		return strlen(data);
	}

    ~my_string() 
	{
		delete[] data;
	}
private:
    char *data;
};

ostream& operator<<(ostream& os,my_string& str)
{
	os << str.data;
	return os;
}

string实现

标签:blog   os   ar   for   2014   c   on   log   r   

原文地址:http://blog.csdn.net/miao65272156/article/details/39855019

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!