zoukankan      html  css  js  c++  java
  • string实现

    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;
    }

  • 相关阅读:
    中间件面试总结
    1.angular js 学习网址
    摄影构图
    mybatis学习(四)
    mybatis学习(三)
    mybatis学习(二)
    mybatis 学习(一)
    mysql 使用过程中出现问题
    springboot
    java 关键字
  • 原文地址:https://www.cnblogs.com/gcczhongduan/p/4199638.html
Copyright © 2011-2022 走看看