现在的位置: 首页 > 综合 > 正文

一个简单的字符串类

2013年02月05日 ⁄ 综合 ⁄ 共 2183字 ⁄ 字号 评论关闭
//str.h
#include<iostream>

#ifndef _STR_H
#define _STR_H

class CStr{
public:
    CStr();
    CStr(
const char*);
    CStr(
int,char);
    CStr(
const CStr&);
    
~CStr();
public:
    
const char* c_str();
    
int length();
public:
    
char& operator[](int);
    
bool operator==(CStr&);
    CStr
& operator=(const CStr&);
    
const CStr operator+(const CStr&);
    
const CStr& operator+=(const CStr&);
    friend std::ostream
& operator<<(std::ostream&,CStr&);
    friend std::istream
& operator>>(std::istream&,CStr&);
private:
    
char *m_str;
    
int m_len;
}
;

#endif

  这个字符串类包含了一些最基本的东西,下面是各个成员函数及重载操作符的实现:

#include"str.h"

CStr::CStr():m_str(NULL),m_len(
0)
{
}


CStr::CStr(
const char *p)
{
    
int size=0;
    
const char *t=p;
    
while(*t++)
        
++size;
    m_str
=new char[size+1];
    m_len
=size;
    memcpy(m_str,p,size
+1);
}


CStr::CStr(
int n,char ch)
{
    m_len
=n;
    m_str
=new char[m_len+1];
    m_str[m_len]
=0;
    memset(m_str,ch,m_len);
}


CStr::CStr(
const CStr &s)
{
    m_str
=new char[s.m_len+1];
    m_len
=s.m_len;
    memcpy(m_str,s.m_str,m_len
+1);
}


CStr::
~CStr()
{
    
if(m_str)
        delete[] m_str;             
}


const char* CStr::c_str()
{
    
return m_str;
}


bool CStr::operator==(CStr &s)
{
    
for(int i=0;i!=m_len;++i){
        
if(*(m_str+i)!=*(s.m_str+i))
            
return false;
    }

    
return true;
}


CStr
& CStr::operator=(const CStr &s)
{
    
if(this==&s)
        
return *this;
    delete[] m_str;
    m_len
=s.m_len;
    m_str
=new char[m_len+1];
    memcpy(m_str,s.m_str,m_len
+1);
    
return *this
}


const CStr CStr::operator+(const CStr &s)
{
    
char *p=new char[m_len+s.m_len+1];
    memcpy(p,m_str,m_len);
    memcpy(p
+m_len,s.m_str,s.m_len+1);
    CStr str(p);
    delete[] p;
    
return str;
}


std::ostream
& operator<<(std::ostream &out,CStr &s)
{
    
out<<s.m_str;
    
return out;
}


std::istream
& operator>>(std::istream &in,CStr &s)
{
    
if(s.m_str){
        delete[] s.m_str;
        s.m_len
=0;
    }

    
char buf[1024];
    
in>>buf;
    
while(buf[s.m_len]){
        
++s.m_len;
    }

    s.m_str
=new char[s.m_len+1];
    memcpy(s.m_str,buf,s.m_len
+1);
    
return in;
}


char& CStr::operator[](int n)
{
    
return m_str[n];
}


const CStr& CStr::operator+=(const CStr &s)
{
    
*this=*this+s;
    
return *this;
}

抱歉!评论已关闭.