MyString
//string.h
#include<iostream>
using std::ostream;
using std::istream;
#ifndef STRING1_H_
#define STRING1_H_
class String{
private:
char *str;
int len;
static int num_strings;
static const int CINLIM = 80;
public:
String(const char *s);
String();
String(const String &st);
~String();
int length() const { return len;}
//overloading
String & operator=(const String & str);
String & operator=(const char *s);
char & operator[](int i);
const char & operator[](int i) const;
//overloading friend
friend bool operator<(const String& st1, const String & st2);
friend bool operator>(const String& st1, const String & st2);
friend bool operator==(const String & st1, const String & st2);
friend ostream & operator<<(ostream & os, const String & st);
friend istream & operator>>(istream & is, String & st);
//static func
static int HowMany();
};
#endif
//string.cxx
#include<iostream>
#include "string1.h"
using std::cout;
using std::cin;
int String::num_strings = 0;
int String::HowMany()
{
return num_strings;
}
String::String(const char *s)
{
len = std::strlen(s);
str = new char[len+1];
std::strncpy(str, s, len);
str[len] = 0;
num_strings++;
}
String::String()
{
len = 0;
str = new char[1];
str[0] = 0;
num_strings++;
}
String::String(const String &st)
len = st.len;
str = new char[len+1];
std::strcpy(str,st.str);
num_strings++;
}
String::~String()
{
--num_strings;
delete [] str;
}
String & String::operator=(const String & str)
{
if(this == &str)
return *this;
delete [] this->str;
len = str.len;
this->str = new char[len+1];
std::strcpy(this->str, str.str);
return *this;
}
String & String::operator=(const char *s)
{
delete[] str;
len = std::strlen(s);
str = new char[len+1];
std::strcpy(str, s);
return *this;
}
char & String::operator[](int i)
{
return str[i];
}
const char & String::operator[](int i) const
{
return str[i];
}
bool operator<(const String & st1, const String & st2)
{
return (std::strcmp(st1.str, st2.str) < 0);
}
bool operator>(const String & st1, const String & st2)
{
return (std::strcmp(st1.str, st2.str) > 0);
}
bool operator==(const String & st1, const String & st2)
{
return (std::strcmp(st1.str, st2.str) == 0);
}
ostream & operator<<(ostream & os, const String & st)
{
os << st.str;
return os;
}
istream & operator>>(istream & is, String & st)
{
char temp[String::CINLIM];
is.get(temp, String::CINLIM);
if(is)
st = temp;
while(is && is.get() != '\n');
return is;
}