• 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;
    }
    
    
    
  • 相关阅读:
    九个令人兴奋的新功能将与Java 9 展示两点
    自学前端开发 新版css时钟效果图
    自学前端,你要的学习资料到了~~~~~~
    Angularjs中ng-repeat与移动端滑动插件iScroll的冲突
    计蒜客学习记录
    明明的随机数
    模板题
    泉州一中复赛模拟
    快速幂模板
    NOIP2013
  • 原文地址:https://www.cnblogs.com/helloweworld/p/3045110.html
Copyright © 2020-2023  润新知