zoukankan      html  css  js  c++  java
  • C++实现String容器的基本功能

      本文只实现String类的构造函数、析构函数、赋值构造函数和赋值函数,其他操作不再详述,一般的笔试面试基本上也只会要求实现这四个函数的功能。

    #include <iostream>
    using namespace std;
    
    class String {
    public:
        //    构造函数
        String(const char *str=NULL);
        //    拷贝构造函数
        String(const String& other);
        //    赋值函数
        String& operator =(const String &other);
        //    析构函数
        ~String(void);
        
    private:
        char *data;
    };
    
    String::String(const char * str) {
        if (str == NULL)
        {
            data = new char[1];
            *data = '';
        }
        else {
            int len = strlen(str) + 1;
            data = new char[len];
            strcpy(data, str);
        }
        
    }
    
    String::String(const String& other) {
        int len = strlen(other.data) + 1;
        data = new char[len];
        strcpy(data, other.data);
    }
    
    String & String::operator=(const String& other) {
        //    判断是不是自赋值
        if (this == &other) 
            return *this;
    
        delete[]data;
    
        int len = strlen(other.data) + 1;
        data = new char[len];
        strcpy(data, other.data);
    
        //    返回本对象的引用
        return *this;
    }
    
    String::~String() {
        delete[]data;
    }
    
  • 相关阅读:
    hdoj 2544 最短路径
    树状数组 hdoj1166
    并查集学习
    1402大数相乘 FFT算法学习!
    hdu1014
    动态规划 简单题dp
    迷宫路径
    简单的动态规划dp
    poj 3282 (bFS)
    背包问题,看不懂,啊!!!!!!!!dp
  • 原文地址:https://www.cnblogs.com/maluning/p/8961854.html
Copyright © 2011-2022 走看看