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

    #include <iostream>
    #include <cstring>
    using namespace std;
    
    class MyString {
    public:
    	MyString();
    	MyString(const char* cstr);
    
    	MyString(const MyString &other);
    	MyString& operator=(const MyString &other);
    
    	size_t length() {
    		return size;
    	}
    
    	friend istream& operator>>(istream &in, const MyString &str);
    	friend ostream& operator<<(ostream &out, const MyString &str);
    
    	~MyString();
    
    protected:
    	char *data;
    	size_t size;
    };
    
    MyString::MyString() {
    	size = 0;
    	data = new char[1];
    	*data = '\0';
    }
    
    MyString::MyString(const char *cstr) {
    	if (cstr != NULL) {
    		size = strlen(cstr);
    		data = new char[size + 1];
    		strcpy(data, cstr);
    	} else {
    		size = 0;
    		data = new char[size + 1];
    		*data = '\0';
    	}
    }
    
    MyString::MyString(const MyString &other) {
    	if (!other.data) {
    		data = new char[other.size + 1];
    		*data = '\0';
    		size = 0;
    	} else {
    		size = other.size;
    		data = new char[1];
    		strcpy(data, other.data);
    	}
    }
    
    MyString& MyString::operator =(const MyString &other) {
    	/*if (this != &other) {
    		size = strlen(other.data);
    		char *temp = new char[size + 1];
    		strcpy(temp, other.data);
    		delete []data;
    		data = temp;
    	}
    	return *this;*/
    
    	if (this != &other) {
    		MyString strTmp(other);
    
    		char *pTmp = strTmp.data;
    		strTmp.data = data;
    		data = pTmp;
    	}
            
            return *this;
    }
    
    MyString::~MyString() {
    	delete []data;
    }
    
    int main()
    {
    	char *s = NULL;
    	MyString str(s);
    
    	return 0;
    }
    
    
    
  • 相关阅读:
    Docker部署Mysql实践
    Docker部署Zookeeper部署集群实践(2)
    Docker部署Zookeeper部署实践(1)
    Docker部署Jenkins 2.285版持续部署集成实践(1)
    Ubuntu18.04安装docker
    Git的配置
    C语言的一些小知识
    线段树模板整理
    关于Kmp
    HDU-2063(二分图匹配模板题)
  • 原文地址:https://www.cnblogs.com/helloweworld/p/3045110.html
Copyright © 2011-2022 走看看