//main.cpp
#include <iostream>
#include "string.h"
using namespace std;
int main()
{
String s1("string 1 .");
String s2 = "string 2 .";
String s3 = s1+s2;
cout << "s1: " << s1.GetBuff() << endl;
cout << "s2: " << s2.GetBuff() << endl;
cout << "s3: " << s3.GetBuff() << endl;
if (s1 > s2)
cout << "s1 > s2" <<endl;
else
if (s1 == s2)
cout << "s1 == s2" << endl;
else
cout << "s1 < s2" << endl;
system("pause");
return 0;
}
//string.h
#ifndef STRING_H
#define STRING_H
#include <OSTREAM>
using namespace std;
class String
{
public:
//构造函数
String();
String( const char * s);
String( const String & str );
//析构函数
~String();
public:
//获取字符串长度
int Length() const{ return m_length; }
//转化到字符指针
char * GetBuff()const{return m_buf; }
//重载各类字符串运算符
String &operator =(String & str);
String &operator =(char * s );
String operator +(const String & str) const;
String operator +(const char * s) const;
bool operator >(const String & str ) const;
bool operator >(const char * s) const;
bool operator ==(const char * s ) const;
bool operator ==(const String & str ) const;
//输出符号 有元重载
friend ostream & operator << (ostream &os, const String & str);
private:
char * m_buf;
int m_length;
};
#endif
//String.cpp
#include "string.h"
#include <CString>
String::String()
{
m_length = 0;
m_buf = new char[1];
m_buf[0] = '\0';
}
String::String(const char * s )
{
m_length = strlen(s);
m_buf = new char[m_length+1];
strcpy(m_buf, s);
}
String::String( const String & str )
{
m_length = str.Length();
m_buf = new char[m_length+1];
memcpy(m_buf, str.m_buf, m_length+1);
}
String::~String()
{
m_length = 0;
delete m_buf;
}
String &String::operator =(char * s)
{
if ( m_buf ) m_buf = NULL;
m_length = strlen(s);
m_buf = new char[m_length+1];
memcpy(m_buf, s, m_length+1);
return *this;
}
String &String::operator =(String & str)
{
m_length = str.Length();
if (m_buf) m_buf = NULL;
m_buf = new char[m_length+1];
strcpy(m_buf, str.m_buf);
return *this;
}
String String::operator +(const char * s) const
{
char * newchar = new char[m_length + strlen(s) +1];
newchar[0] = '\0';
strcat(newchar, m_buf);
strcat(newchar, s);
String ret( newchar );
delete newchar;
return ret;
}
String String::operator +(const String & str) const
{
char * newchar = new char[m_length+str.m_length+1];
newchar[0] = '\0';
strcat(newchar, m_buf);
strcat(newchar, str.m_buf);
// newchar[m_length+str.m_length] = '\0';
String ret(newchar);
return ret;
}
bool String::operator >(const char * s) const
{
return strcmp(m_buf, s) > 0;
}
bool String::operator >(const String & str) const
{
return strcmp( m_buf, str.m_buf) > 0;
}
bool String::operator ==(const char * s) const
{
return (m_length == strlen(s) && strcmp(m_buf, s) == 0);
}
bool String::operator ==(const String & str) const
{
return (m_length == str.Length() && strcmp(m_buf, str.m_buf) == 0);
}
ostream & operator <<(ostream &os, const String & str)
{
if(str.GetBuff())
os<<str.GetBuff();
return os;
}