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;
    }
    
    
    
  • 相关阅读:
    MATLAB 编程风格指南及注意事项
    Redis笔记
    HDU-5706
    【sqli-labs】 less4 GET
    【sqli-labs】 less3 GET
    【sqli-labs】 less2 GET
    【sqli-labs】 less1 GET
    Ubuntu14.04环境下java web运行环境搭建
    Android进度条控件ProgressBar使用
    Android中DatePicker与TimePicker用法讲解(包括DatePickerDialog与TimePickerDialog)
  • 原文地址:https://www.cnblogs.com/helloweworld/p/3045110.html
Copyright © 2011-2022 走看看