zoukankan      html  css  js  c++  java
  • 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;
    }
    

      

  • 相关阅读:
    功能点方法
    学数答题160908-数论不等式
    学数答题160903-函数方程
    学数答题160906-不等式最值
    学数答题160905-函数方程
    学数答题160904-不等式
    学数答题160903-三角函数
    kitti-b站教程
    kitti数据集介绍
    SLAM:理论与实践
  • 原文地址:https://www.cnblogs.com/Oscar67/p/9562444.html
Copyright © 2011-2022 走看看