码迷,mamicode.com
首页 > 编程语言 > 详细

C++中String类的实现

时间:2015-06-08 09:48:04      阅读:154      评论:0      收藏:0      [点我收藏+]

标签:string类


#pragma once
#include <iostream>
#include <string.h>
#define _SIZE_ 100
using namespace std;
class Count
{
public:
    Count() :count(1){}
    void add()
    {
        count++;
    }
    void dec()
    {
        count--;
    }
    int getcount()
    {
        return count;
    }
private:
    int count;
};
class String
{
public:
    String(const char *s = "")
    {
        copy(ptr,s);
    }
    String(const String &s)
    {
        copy(ptr,s.ptr);
        counT.add();
    }
    String& operator=(const String& s)
    {
        if (this != &s)
        {
            String tmp(s.ptr);
            char *temp = tmp.ptr;
            tmp.ptr = ptr;
            ptr = temp;//内存安全。
        }
        return *this;
    }
    ~String()
    {
        if (counT.getcount() == 1)
        {
            cout << ptr << "  :del" << endl;
            delete[]ptr;
        }
    }
    friend ostream& operator<<(ostream& os, String &s)
    {
        os << s.ptr;
        return os;
    }
    friend istream& operator>>(istream& is, String &s)
    {
        char buf[_SIZE_];
        is >> buf;
        s.copy(s.ptr,buf);
        return is;
    }
    String& operator += (const String &s)
    {
        char *buf = new char[strlen(ptr) + strlen(s.ptr) + 1];
        strcpy(buf, ptr);
        strcat(buf,s.ptr);
        copy(ptr,buf);
        return *this;
    }
    String& operator +=(const char *str)
    {
        char *buf = new char[strlen(ptr) + strlen(str) + 1];
        strcpy(buf,ptr);
        strcat(buf,str);
        copy(ptr,buf);
        return *this;
    }
    bool operator != (const String &s)
    {
        return strcmp(ptr,s.ptr);
    }
    bool operator ==(const String &s)
    {
        return !strcmp(ptr,s.ptr);
    }
private:
    void copy(char *&p,const char *s)
    {
        p = new char[strlen(s) + 1];
        strcpy(p,s);
    }
private:
    char *ptr;
    Count counT;
};

#include <iostream>
#include "String.h"
using namespace std;
int main()
{
    String s("123");
    String s1("456");
    s += s1;
    return 0;
}

“`

C++中String类的实现

标签:string类

原文地址:http://blog.csdn.net/liuhuiyan_2014/article/details/46406535

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!