• string_自定义


    string类的基本操作

    // Study.cpp: 定义控制台应用程序的入口点。
    //
    
    #include "stdafx.h"
    #include <iostream>
    #include <vector>
    #include <unordered_map>
    #include <unordered_set>
    #include <queue>
    #include <string>
    #include <algorithm>
    #include <sstream>
    using namespace std;
    
    class myString;
    class myString {
    	friend ostream& operator<<(ostream& out, const myString& ss);
    public:
    	//普通构造函数
    	myString(const char* word=nullptr)
    	{
    		if (word == nullptr)
    		{
    			p = new char;
    			//需要判断是否成功分配内存  p == nullptr ??
    			if (p == nullptr)
    			{
    				cout << "申请内存失败 " << endl;
    				return;
    			}
    			*p = '';
    			length = 0;
    		}
    		else
    		{
    			length = strlen(word);
    			p = new char[length+1];
    			//需要判断是否成功分配内存  p == nullptr ??
    			if (p == nullptr)
    			{
    				cout << "申请内存失败 " << endl;
    				return;
    			}
    			strcpy(p, word);
    		}
    
    
    	}
    	//拷贝构造函数
    	myString(const myString & ss)
    	{
    		p = new char [ss.length + 1];
    		//需要判断是否成功分配内存  p == nullptr ??
    		if (p == nullptr)
    		{
    			cout << "申请内存失败 " << endl;
    			return;
    		}
    		strcpy(p, ss.p);
    		length = ss.length;
    	}
    	myString& operator=(const myString &ss)
    	{
    		//检查自赋值
    		if (this == &ss)
    			return *this;
    
    		//删除原来的内存资源
    		delete []p;
    
    		length = ss.length;
    		p = new char[length + 1];
    		//需要判断是否成功分配内存  p == nullptr ??
    		if (p == nullptr)
    		{
    			cout << "申请内存失败 " << endl;
    			return *this;
    		}
    		strcpy(p, ss.p);
    		return *this;
    	}
    
    	~myString()
    	{
    		delete []p;
    	}
    private:
    	char* p;
    	int length;
    };
    ostream& operator<<(ostream& out, const myString& ss)
    {
    	out << (ss.p);
    	return out;
    }
    
    
    int main()
    {
    
    	myString a("Hello World !");
    	myString b("Let's go ");
    	cout << "a : "<< a << endl;
    	cout << "b : " << b << endl;
    	myString c(b);
    	cout << "c : " << c << endl;
    	a = b;
    	cout << "a : " << a << endl;
    
    	string x("X");
    	cout << x.substr(0, 2) << endl;
    	system("pause");
    	return 0;
    }
    

      

  • 相关阅读:
    System.StringOfChar 反复字符
    System.Concat 连接字符串
    学习 TList 类的实现[5]
    raise 语句: 抛出异常
    System.Move 移动内存块
    学习 TList 类的实现[6]
    System.Pos 搜索子串的位置
    System.FillChar 填充字节
    学习 TList 类的实现[4]
    不停止的认识我们自己。。。。
  • 原文地址:https://www.cnblogs.com/Oscar67/p/9562444.html
Copyright © 2020-2023  润新知