首页 > 其他 > 详细

string实现

时间:2015-01-03 17:04:30      阅读:123      评论:0      收藏:0      [点我收藏+]
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实现

原文:http://www.cnblogs.com/gcczhongduan/p/4199638.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!