(教学版本,main函数可以自己写)
MyString.h
#ifndef __MYSTRING_H__
#define __MYSTRING_H__
#include <iostream>
using namespace std;
class MyString
{
friend ostream & operator<<(ostream& out, const MyString& str);
friend istream & operator>>(istream& in, const MyString& str);
public:
MyString(int len=0);
MyString(const char *p);
MyString(const MyString & str);
~MyString();
public:
MyString& operator=(const char *p);
MyString& operator=(const MyString &str);
char& operator[](const int index);
bool operator==(const char *p) const;
bool operator==(const MyString& str) const;
bool operator!=(const char *p) const;
bool operator!=(const MyString& str) const;
bool operator<(const char *p) const;
bool operator<(const MyString& str) const;
bool operator>(const char *p) const;
bool operator>(const MyString& str) const;
public:
char *c_str()
{
return m_p;
}
const char *c_str2()
{
return m_p;
}
int length()
{
return m_len;
}
private:
int m_len;
char *m_p;
};
#endif
MyString.cpp
#include "MyString.h"
#include <string.h>
ostream & operator<<(ostream& out, const MyString& str)
{
out << str.m_p;
return out;
}
istream & operator>>(istream& in, const MyString& str)
{
in >> str.m_p;
return in;
}
MyString::MyString(int len)
{
if (len == 0)
{
m_len = 0;
m_p = new char[m_len + 1];
strcpy(m_p, "");
}
else
{
m_len = len;
m_p = new char[m_len + 1];
memset(m_p, 0, m_len+1);
}
}
MyString::MyString(const char *p)
{
if (p == NULL)
{
m_len = 0;
m_p = new char[m_len + 1];
strcpy(m_p, "");
}
else