头文件
#ifndef STRING_H
#define STRING_H
#include<iostream>
using namespace std;
class String
{
friend istream& operator>>(istream&,String&);
friend ostream& operator<<(ostream&,const String&);
public:
String(char* str = "");
String(const String&);
virtual ~String();
void setStr(const char*);
char* getStr()const {return str;}
int getSize()const {return size;}
String& operator+=(const String&);
bool operator==(const String&);
operator int();
private:
char* str;
int size;
};
#endif // STRING_H
.cpp文件
#include "String.h"
#include<cstring>
#include<iostream>
#include<cstdlib>
#include<climits>
using namespace std;
String::String(char* _str)
{
setStr(_str);
}
String::String(const String& result)
{
setStr(result.str);
}
void String::setStr(const char* _str)
{
//if(str!=NULL) delete str;
str = new char[strlen(_str)+1];
strcpy(str,_str);
size = strlen(_str);
}
String::~String()
{
delete str;
}
String& String::operator+=(const String& souce)
{
if(this==&souce)
{
return *this;
}
char* temp = new char[souce.getSize()+size+1];
strcpy(temp,this->getStr());
strcat(temp, souce.getStr());
if (str!=NULL) delete str;
str = new char[souce.getSize()+size+1];
strcpy(this->getStr(),temp);
size = souce.getSize()+size;
delete temp;
return *this;
}
bool String::operator==(const String& souce)
{
bool flag = true;
if(size!=souce.getSize())
{
flag = false;
return flag;
}
int count = 0;
char* temp = souce.getStr();
while(temp[count]!='\0'&&str[count]!='\0')
{
if(temp[count]!=str[count])
{
flag = false;
}
count++;
}
return flag;
}
istream& operator>>(istream& in,String& souce)
{
cout<<"Please input the string:"<<endl;
char* temp = new char[sizeof(char)*100];
in>>temp;
souce.setStr(temp);
delete temp;
return in;
}
ostream& operator<<(ostream& out,const String& souce)
{
out<<souce.getStr()<<endl;
out<<souce.getSize()<<endl;
return out;
}
String::operator int()
{
int temp = 0,count = 0;
if(str[0]=='-'||str[0]=='+')
{
count++;
}
while(str[count]!='\0')
{
if(str[count]<'0'||str[count]>'9')
{
cout<<"Can't convert int!!"<<endl;
exit(0);
}
int tmp;
tmp = str[count]-'0';
temp=temp*10;
temp+=tmp;
if(temp<0||(temp+tmp)>INT_MAX)
{
//cout<<temp<<endl;
if(str[0]=='-'){
if(temp==INT_MIN)
{
return temp;
}
cout<<"The number is too small!!"<<endl;
}else{
cout<<"The number is too big!!"<<endl;
}
exit(0);
}
count++;
}
if(str[0]=='-')
{
return 0-temp;
}
return temp;
}
很简单的实现