各种问题,求解释
#include<iostream>using std::ostream;
using std::istream;
#ifndef STRING_H_
#define STRING_H_
class String
{
private:
char *str;
int len;
static int num_string;
public:
String(char *s);
String();
String(const String &);
~String();
int length()const {return len;};
String & operator=(const String &);
String & operator=(const char *);
char & operator[](int i);
const char & operator[](int i)const;
friend bool operator<(const String &st1,const String &st2);
friend bool operator>(const String &sti,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,const String & st);
};
#endif
#include<cstring>
#include"String.h"
using std::cout;
using std::cin;
int String::num_string=0;
String::String(char *s)
{
len=std::strlen(s);
str=new char[len+1];
std::strcpy(str,s);
num_string++;
}
String::String()
{
len=4;
str=new char[1];
str[0]='\0';
num_string++;
}
String::String(const String & s)
{
num_string++;
len=s.len;
str=new char[len+1];
std::strcpy(str,s.str);
}
String::~String()
{
--num_string;
delete [] str;
}
String & String::operator=(const String &st)
{
if(this==&st)
return *this;
delete[]str;
len=st.len;
str=new char[len+1];
std::strcpy(str,st.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,const String & st)
{
char temp[80];
is.get(temp,80);
if(is)
st=temp;
while(is&&is.get()!='\n')
continue;
return is;
}
#include<iostream>
#include"String.h"
using namespace std;
int main()
{
char *lyj="my name is lyj";
String s1("my name is dyq");
String s2(lyj);
String s3=s2;
String s4;
string s5;
s4="my name is dyq";
cout<<"输入s5:\n";
cin>>s5;
cout<<s1<<" s1\n";
cout<<s2<<" s2\n";
cout<<s3<<" s3\n";
cout<<s4<<" s4\n";
cout<<s5<<" s5\n";
if(s1==s4)
cout<<"s1=s4\n";
else
cout<<"错误\n";
return 0;
}