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

  • 相关阅读:
    这个网站的设计太独特了
    mybatis—— 一个空格引发的血案
    Java IO--实现文件的加密解密
    Intellij IDEA如何生成JavaDoc--转载
    Java 在循环里发生异常会跳出循环
    idea格式化代码快捷键
    idea创建类时默认添加头部注释信息
    maven-helper解决依赖冲突
    Octotree插件
    idea .gitignore(git文件忽略)
  • 原文地址:https://www.cnblogs.com/WHUT-Simon/p/11732901.html
Copyright © 2011-2022 走看看