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;
    }
    
  • 相关阅读:
    Python基本数据类型
    Python内存相关
    Python运算符和编码
    js比较日期大小 判断日期
    js判断一个数是不是正整数
    sql查询排序
    js获取select标签选中的值
    PL/sql配置相关
    搜狗的好玩用法
    Oracle数据库中的dual表
  • 原文地址:https://www.cnblogs.com/maluning/p/8961854.html
Copyright © 2011-2022 走看看