zoukankan      html  css  js  c++  java
  • C++primer 练习13.44

    13.44:编写标准库string类的简化版本,命名为String。你的类应该至少有一个默认构造函数和一个接受C

    风格字符串指针参数的构造函数。使用allocator为你的String类分配所需内存

    String.h头文件

    #pragma once
    #include<memory>
    #include<iostream>
    using namespace std;
    
    class String
    {
        friend ostream& operator<<(ostream& os, String &str)//运算符重载,实现输出
        {
            auto beg = str.elements;
            for (;beg != str.first_free;)
                os << *(beg++);
            return os;
        }
    public:
        String() :elements(nullptr), first_free(nullptr), cap(nullptr) {}          //    默认构造函数,得到一个空字符串
        String(char* chptr); //C风格字符串指针参数的构造函数
        void free();         //析构函数的辅助函数
        ~String();           //析构函数,因为用了allocator,必须要定义析构函数
    private:
        allocator<char> alloc;
        char* elements;      //指向字符串首元素的指针
        char* first_free;    //指向字符串尾元素之后的指针
        char* cap;           //指向尾后位置的指针
    };
    
    String::String(char *chptr)
    {
        size_t len = 0;
        for (char *ch = chptr;'' != *ch;++ch, ++len);//得到字符串的长度
        elements=alloc.allocate(len);                  //分配一个长的为len的空间
        first_free = elements;
        for (size_t i = 0;i < len;++i)                 //将元素构造到港分配的空间中去
        {
            alloc.construct(first_free++, *(chptr++));
        }
        cap = first_free;
    }
    
    void String::free()
    {
        if (elements)                   //不能传递给deallocate一个空指针
        {
            size_t len = cap - elements;
            for (;first_free != elements;)  //逆序销毁旧元素
                alloc.destroy(--first_free);
            alloc.deallocate(elements, len);
        }
    }
    
    String::~String()
    {
        free();
    }

    主函数验证

    // 13_44.cpp : 定义控制台应用程序的入口点。
    //
    
    #include "stdafx.h"
    #include"String.h"
    #include<iostream>
    using namespace std;
    
    int main()
    {
        String str0,str1("haha");
        cout << str0 << "
    " << str1 << endl;
        return 0;
    }
  • 相关阅读:
    python paramiko模块学习分享
    中国大数据市场规模分析及预测
    中国大数据市场规模分析及预测
    显著性水平 置信度 置信区间 实例讲解
    显著性水平 置信度 置信区间 实例讲解
    加密算法
    Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry 'qingmu' for key 'PRIMARY'
    spring Security的自定义用户认证
    spring的面试题
    solr和ElasticSearch(ES)的区别?
  • 原文地址:https://www.cnblogs.com/csudanli/p/5388604.html
Copyright © 2011-2022 走看看