简单版的String类,旨在说明>> <<重载
#include <iostream> //#include <cstring>//包含char*的字符串处理函数 using namespace std; class String { public: String(){p=NULL;} String(char *str); void diaplay(); friend bool operator>(String &str1,String &str2);//重载>操作符 friend ostream & operator <<(ostream&,String &str); friend istream & operator >>(istream&,String &str); private: char *p; }; String::String(char *str) { p=str; } void String::diaplay() { cout<<p; } bool operator>(String &str1,String &str2) { if (strcmp(str1.p,str2.p)>0) { return true; } else return false; } ostream& operator <<(ostream& output,String &str) { output<<str.p; return output; } istream& operator >>(istream& input,String &str) { //input>>str.p;//没有分配空间,无法读入。 str.p=new char[256]; input>>str.p; return input;// // char q[256]; // input>>q; // //p.length =strlen(q); // str.p=new char[strlen(q)+1]; // strcpy(str.p,q); // return input; } int main() { String str1("Hello,pig!"),str2; cin>>str2; str1.diaplay(); bool b=str1>str2; cout<<' '<<b<<endl; cout<<str2<<endl; }
重载>> <<函数只能作为类的类的友元函数,其形式如下:
istream& operator >>(istream& ,自定义类 &);
ostream& operator <<(ostream& ,自定义类 &);
重载运算法作为类成员函数还是类友元函数区别:
1 作为类成员函数必须满足运算表达式第一个参数是一个类对象,而且返回值与该对象同类型。
故一般将单目操作符重载为成员函数,双目操作符重载为友元函数。
String 类较完整实现:
#include <iostream> //#include <cstring>//包含char*的字符串处理函数 using namespace std; class String { public: String(){p=NULL;len=0;} String(int); String(char *str); String (String&); ~String(){delete[] p;} void Clear();//清空本串 int mystrlen(); bool IsEmpty();//判断本串是否为空 String Substr(int index,int count);//从index开始提取count个字符的字串 int Find(char c,int start);//从下标start开始找到c后,返回字符c 在本串的下标 char & operator [](int i);//重载[]操作符 operator char *();//将String类对象转换为普通字符串 friend bool operator>(String &str1,String &str2);//重载>操作符 friend ostream & operator <<(ostream&,String &str); friend istream & operator >>(istream&,String &str); private: char *p;//字符串指针 int len;//字符串长度,不包含最后的 }; String::String(int length) { len=length; p=new char[length+1]; } String::String(char *str) { if (str==NULL) { len=0; p=NULL; } else { len=strlen(str); p=new char[len+1]; strcpy(p,str);//深拷贝 } //p=str;//只写这个是浅拷贝,只拷贝了指针 } String::String(String &other) { len=other.len; p=new char[len+1]; strcpy(p,other.p); } bool String::IsEmpty() { return (!this->len); } void String::Clear() { if (!IsEmpty()) { delete[]p; len=0; } } int String::mystrlen() { return len; } int String::Find(char c,int start) { int i; if (start>len) cout<<"超出范围"<<endl; //return NULL; else { for (i =start;i<len;++i) { if (p[i]==c) break; } return i; } } String String::Substr(int index,int count) { if (index+count>len) cout<<"超出范围"<<endl; else { String str(count); str.len=count; for (int i=0;i<count;i++,index++) str.p[i]=p[index]; str.p[count]='