| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 2497 人关注过本帖, 2 人收藏
标题:自定义string类
只看楼主 加入收藏
lyb661
Rank: 5Rank: 5
等 级:贵宾
威 望:18
帖 子:47
专家分:83
注 册:2018-12-12
结帖率:71.43%
收藏(2)
 问题点数:0 回复次数:1 
自定义string类
//自定义String类 注意分别编译

///String.h
#ifndef MY_String_H_
#define MY_String_H_
#include<iostream>
using std::istream;
using std::ostream;
class String
{
public:
String( const char *cString = "" ); // Constructor
String( char ch ); // Constructor
String( const String & str ); // Copy constructor
~String( ) // Destructor
{ delete [ ] buffer; }
const String & operator= ( const String & rhs ); // Copy
const String & operator+=( const String & rhs ); // Append
const char *c_str( ) const // Return C-style String
{ return buffer; }
int length( ) const // Return String length
{ return strLength; }
char operator[]( int k ) const; // Accessor operator[]
char & operator[]( int k ); // Mutator operator[]
friend istream & operator>>( istream & in, String & str ); // Input
private:
char *buffer; // storage for characters
int strLength; // length of String (# of characters)
int bufferLength; // capacity of buffer
};
ostream & operator<<( ostream & out, const String & str ); // Output
istream & getline( istream & in, String & str ); // Read line
istream & getline( istream & in, String & str, char delim ); // Read line
String operator+( const String & lhs, const String & rhs ); // Concatenation
bool operator==( const String & lhs, const String & rhs ); // Compare ==
bool operator!=( const String & lhs, const String & rhs ); // Compare !=
bool operator< ( const String & lhs, const String & rhs ); // Compare <
bool operator<=( const String & lhs, const String & rhs ); // Compare <=
bool operator> ( const String & lhs, const String & rhs ); // Compare >
bool operator>=( const String & lhs, const String & rhs ); // Compare >=
#endif



///String.cpp
#include <cstring>
#include <cctype>
#include "String.h"
using std::cerr;
String::String( const char * cString )
{
if( cString == NULL )
cString = "";
strLength = strlen( cString );
bufferLength = strLength + 1;
buffer = new char[ bufferLength ];
strcpy( buffer, cString );
}
String::String( const String & str )
{
strLength = str.length( );
bufferLength = strLength + 1;
buffer = new char[ bufferLength ];
strcpy( buffer, str.buffer );
}
String::String( char ch )
{
strLength = 1;
bufferLength = strLength + 1;
buffer = new char[ bufferLength ];
buffer[ 0 ] = ch;
buffer[ 1 ] = '\0';
}/*
const String & String::operator=( const String & rhs )
{
if( this != &rhs )
{
if( bufferLength < rhs.length( ) + 1 )
{
delete [ ] buffer;
bufferLength = rhs.length( ) + 1;
buffer = new char[ bufferLength ];
}
strLength = rhs.length( );
strcpy( buffer, rhs.buffer );
}
return *this;
}*/
const String& String::operator=(const String& rhs)
{
if(this==&rhs)
return *this;
delete []buffer;
strLength=rhs.length();
bufferLength=strLength+1;
buffer=new char[bufferLength];
strcpy(buffer,rhs.buffer);
return *this;
}
/*
const String & String::operator+=( const String & rhs )
{
if( this == &rhs )
{
String copy( rhs );
return *this += copy;
}
int newLength = length( ) + rhs.length( );
if( newLength >= bufferLength )
{
bufferLength = 2 * ( newLength + 1 );
char *oldBuffer = buffer;
buffer = new char[ bufferLength ];
strcpy( buffer, oldBuffer );
delete [ ] oldBuffer;
}
strcpy( buffer + length( ), rhs.buffer );
strLength = newLength;
return *this;d
}*/
const String& String::operator+=(const String& rhs)
{
strLength+=rhs.length();
bufferLength=strLength+1;
char* oldBuffer=buffer;
buffer=new char[bufferLength];
strcpy(buffer,oldBuffer);
delete []oldBuffer;
strcat(buffer,rhs.buffer);
return *this;
}
char & String::operator[ ]( int k )
{
if( k < 0 || k >= strLength )
cerr<<"StringIndexOutOfBoundsException( k, length( ) )";
return buffer[ k ];
}
char String::operator[ ]( int k ) const
{
if( k < 0 || k >= strLength )
cerr<<"StringIndexOutOfBoundsException( k, length( ) )";
return buffer[ k ];
}
String operator+( const String & lhs, const String & rhs )
{
String result = lhs;
result += rhs;
return result;
}
ostream & operator<<( ostream & out, const String & str )
{
return out << str.c_str( );
}/*
istream & operator>>( istream & in, String & str )
{
char ch[256];
in>>ch;
str.strLength=strlen(ch);
str.bufferLength=str.strLength+1;
delete []str.buffer;
str.buffer=new char[str.bufferLength];
strcpy(str.buffer,ch);
return in;
}*/
istream & operator>>( istream & in, String & str )
{
char ch;
str = "";
in >> ch;
if( !in.fail( ) )
{
do
{
str += ch;
in.get( ch );
} while( !in.fail( ) && !isspace( ch ) );
if( isspace( ch ) ) // put whitespace back on the stream
in.putback( ch );
}
return in;
}
istream & getline( istream & in, String & str, char delim )
{
char ch;
str = ""; // empty String, will build one char at-a-time
while( in.get( ch ) && ch != delim )
str += ch;
return in;
}
istream & getline( istream & in, String & str )
{
return getline( in, str, '\n' );
}
bool operator==( const String & lhs, const String & rhs )
{
return strcmp( lhs.c_str( ), rhs.c_str( ) ) == 0;
}
bool operator!=( const String & lhs, const String & rhs )
{
return strcmp( lhs.c_str( ), rhs.c_str( ) ) != 0;
}
bool operator<( const String & lhs, const String & rhs )
{
return strcmp( lhs.c_str( ), rhs.c_str( ) ) < 0;
}
bool operator<=( const String & lhs, const String & rhs )
{
return strcmp( lhs.c_str( ), rhs.c_str( ) ) <= 0;
}
bool operator>( const String & lhs, const String & rhs )
{
return strcmp( lhs.c_str( ), rhs.c_str( ) ) > 0;
}
bool operator>=( const String & lhs, const String & rhs )
{
return strcmp( lhs.c_str( ), rhs.c_str( ) ) >= 0;
}


///Main.cpp
#include "String.h"
using std::cin;
using std::cout;
using std::endl;
int main( )
{
String d;
cout<<"enter a string:\n";
cin>>d;
cout<<d<<endl;
String a = "hello";
String b = "world";
String c;
c = a + " "+b;
cout << "c is: " << c << endl;
cout << "c is: " << c.c_str( ) << endl;
cout << "c is: ";
for( int i = 0; i < c.length( ); i++ )
cout << c[ i ];
cout << endl;
return 0;
}
搜索更多相关主题的帖子: string const char buffer operator 
2019-04-17 12:35
uouo99
Rank: 2
等 级:论坛游民
威 望:3
帖 子:30
专家分:98
注 册:2019-9-30
收藏
得分:0 
自定义带引用计数的String类雏形

程序代码:
#include <iostream>
#include <vector>
class RCObject
{
public:
    RCObject();
    RCObject(const RCObject& rhs);
    RCObject& operator=(const RCObject& rhs);
    virtual ~RCObject() = 0;
    void addRefernce();
    void removeReference();
    void markUnshareable();
    bool isShareable() const;
    bool isShared() const;
private:
    int refCount;
    bool shareable;
};
RCObject::RCObject():refCount(0),shareable(true){}
RCObject::RCObject(const RCObject&):refCount(0),shareable(true){}
RCObject& RCObject::operator=(const RCObject&)
{
    return *this;
}
RCObject::~RCObject() {}
void RCObject::addRefernce()
{
    ++refCount;
}
void RCObject::removeReference()
{
    if (--refCount == 0) delete this;
}
void RCObject::markUnshareable()
{
    shareable = false;
}
bool RCObject::isShareable() const
{
    return shareable;
}
bool RCObject::isShared() const
{
    return refCount > 1;
}

template<typename T>
class RCPtr
{
public:
    RCPtr(T* realPtr = 0);
    RCPtr(const RCPtr& rhs);
    ~RCPtr();

    RCPtr& operator=(const RCPtr& rhs);

    T* operator->() const;
    T& operator*() const;
private:
    T *pointee;
    void init();
};
template<typename T>
RCPtr<T>::RCPtr(T* realPtr):pointee(realPtr)
{
    init();
}
template<typename T>
RCPtr<T>::RCPtr(const RCPtr& rhs) : pointee(rhs.pointee)
{
    init();
}

template<typename T>
inline void RCPtr<T>::init()
{
    if (pointee)
    {
        return;
    }
    if (pointee->isShareable() == false)
    {
        pointee = new T(*pointee);
    }
    pointee->addRefernce();
}
template<typename T>
RCPtr<T>& RCPtr<T>::operator=(const RCPtr& rhs)
{
    if (pointee != rhs.pointee)
    {
        if (pointee)
        {
            pointee->removeReference();
        }
        pointee = rhs.pointee;
        init();
    }
    return *this;
}
template<typename T>
RCPtr<T>::~RCPtr()
{
    if (pointee) pointee->removeReference();
}
template<typename T>
T* RCPtr<T>::operator->() const
{
    return pointee;
}
template<typename T>
T& RCPtr<T>::operator*() const
{
    return *pointee;
}
class String
{
public:
    String(const char *initValue = "");
    class CharProxy
    {
    public:
        CharProxy(String& str, int index);

        CharProxy& operator=(const CharProxy& rhs);
        CharProxy& operator=(char c);
        char * operator&();
        const char * operator&() const;
        operator char() const;
    private:
        void assignValue(char &c);
        void makeCopy();
        String& theString;
        int charIndex;
    };
    //const char& operator[](int index) const;
    //char& operator[](int index);
    const CharProxy operator[](int index) const;
    CharProxy operator[](int index);
    friend class CharProxy;
private:
    struct StringValue :public RCObject
    {
        //int refCount;
        char *data;

        StringValue(const char *initValue);
        StringValue(const StringValue& rhs);
        void init(const char *initValue);
        ~StringValue();
    };
    RCPtr<StringValue> value;
};
String::String(const char *initValue) :value(new StringValue(initValue))
{
}
//const char& String::operator[](int index) const
//{
//    return value->data[index];
//}
//char& String::operator[](int index)
//{
//    if (value->isShared())
//    {
//        value = new StringValue(value->data);
//    }
//    value->markUnshareable();
//    return value->data[index];
//}

const String::CharProxy String::operator[](int index) const
{
    return CharProxy(const_cast<String&>(*this), index);
}
String::CharProxy String::operator[](int index)
{
    return CharProxy(*this, index);
}
String::CharProxy::CharProxy(String& str, int index) :theString(str), charIndex(index) {}
String::CharProxy::operator char() const
{
    return theString.value->data[charIndex];
}
void String::CharProxy::assignValue(char &c)
{
    makeCopy();
    theString.value->data[charIndex] = c;
}
String::CharProxy& String::CharProxy::operator=(const CharProxy& rhs)
{
    assignValue(rhs.theString.value->data[rhs.charIndex]);
    return *this;
}
String::CharProxy& String::CharProxy::operator=(char c)
{
    assignValue(c);
    return *this;
}

void String::CharProxy::makeCopy()
{
    if (theString.value->isShared())
    {
        theString.value = new StringValue(theString.value->data);
    }
}
const char* String::CharProxy::operator&() const
{
    return &(theString.value->data[charIndex]);
}

char* String::CharProxy::operator&()
{
    makeCopy();
    theString.value->markUnshareable();
    return &(theString.value->data[charIndex]);
}

void String::StringValue::init(const char *initValue)
{
    data = new char[strlen(initValue) + 1];
    strcpy(data, initValue);
}
String::StringValue::StringValue(const char *initValue)//:refCount(1)
{
    init(initValue);
}
String::StringValue::StringValue(const StringValue& rhs)
{
    init(rhs.data);
}
String::StringValue::~StringValue()
{
    delete[] data;
}



2019-10-02 12:54
快速回复:自定义string类
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.053559 second(s), 9 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved