zoukankan      html  css  js  c++  java
  • String类(1)

    #include <string.h>
    #include <iostream>
    
    using std::cout;
    using std::endl;
    
    class String
    {
    public:
        String()//显示定义无参构造函数
        : _pstr(new char[1]())
        {
            strcpy(_pstr,"0");
            cout << "String()" << endl;
        }
    
        String(const char *pstr)//构造函数
        : _pstr(new char[strlen(pstr)+ 1]()) 
        {
            strcpy(_pstr,pstr);
            cout << "String(const char *pstr)" << endl;
        }
    
        String(const String & rhs)//拷贝构造函数 深拷贝
        : _pstr(new char[strlen(rhs._pstr)+1]())
        {
            strcpy(_pstr, rhs._pstr);
            cout << "String(const String &)" << endl;
        }
    
        String & operator=(const String & rhs)//赋值函数
        {
            if(this != &rhs) {//判断是否是自复制
                cout << "String & operator=(const String &)" << endl;
                delete [] _pstr;//回收左操作申请的空间
    
                //再进行深拷贝
                _pstr = new char[strlen(rhs._pstr) + 1]();
                strcpy(_pstr, rhs._pstr);
            }
            return *this;
        }
    
        ~String()//析构函数
        {
            if(_pstr)
                delete [] _pstr;
    
            cout << "~String()" << endl;
        }
    
        void print()
        {
            printf("pstr = %p
    ", _pstr);
            cout << "pstr:" << _pstr << endl;
        }
    
    private:
        char * _pstr;
    };

    为什么要使用 strlen(s) + 1?

    在 C 语言中,字符串是以空字符做为终止标记(结束符)的。所以,C 语言字符串的最后一个字符一定是 。请确保所有的字符串都是按照这个约定来存储的,不然程序就会因为莫名其妙的错误退出。strlen 函数返回的是字符串的实际长度(所以不包括结尾的  终止符)。所以为了保证有足够的空间存储所有字符,我们需要在额外 +1。如"abc",占四个字节,strlen的值是3

    为什么+1,sizeof和strlen的区别:
    https://blog.csdn.net/Young__Fan/article/details/89478126

  • 相关阅读:
    计算机原理及硬件介绍
    python学习之由
    IDEA如何设置JVM参数
    Java函数式编程
    ubuntu更换源
    ubuntu 安装时没有设置root密码,如何登陆root
    ubuntu16.04镜像下载地址
    Elasticsearch Search APIs
    Elasticsearch Document APIs
    Elasticsearch搜索
  • 原文地址:https://www.cnblogs.com/WHUT-Simon/p/11732901.html
Copyright © 2011-2022 走看看