標籤:c++ 重載string
在c++中有一個新定義的類型string,可以不用那麼麻煩的操作字串,並且一些進階的運算子多載讓她的使用更加便捷
下面是String類的定義和成員函數的定義:
#ifndef operator_operator_h#define operator_operator_h#include<iostream>#include<string.h>using namespace std;class String{ friend ostream& operator<<(ostream &out, const String &s); friend istream& operator>>(istream &in, String &s);public: String(const char *str = NULL) { if(str == NULL) { m_data = new char[1]; m_data[0] = '\0'; } else { m_data = new char[strlen(str)+1]; strcpy(m_data,str); } } String(const String &s) { m_data = new char[strlen(s.m_data)+1]; strcpy(m_data,s.m_data); } String& operator=(const String &s) { if(this != &s) { free(m_data); m_data = new char[strlen(s.m_data)+1]; strcpy(m_data,s.m_data); } return *this; } ~String() { delete []m_data; } friend ostream& operator<<(ostream &out, const String &s) { out<<s.m_data; return out; } friend istream& operator>>(istream &in, String &s) { in>>s.m_data; return in; } String operator+(const String &s); //s = s1 + s2 String operator+=(const String &s); //s1 += s2 char& operator[](int index); bool operator==(String &s); bool operator!=(String &s); bool operator>(String &s); //s1 > s2 bool operator<=(String &s); bool operator<(String &s); bool operator>=(String &s);private: char *m_data;};String String::operator+=(const String &s) //s1 += s2{ m_data = new char[sizeof(m_data)+1]; strcat(m_data,s.m_data); return *this;}String String::operator+(const String &s)//s = s1 + s2{ strcat(m_data, s.m_data); return *this;}bool String::operator==(String &s){ if(strcmp(m_data, s.m_data)==0) return true; return false;}bool String::operator!=(String &s){ if(strcmp(m_data,s.m_data)!=0) return true; return false;}bool String::operator>(String &s) //s1 > s2{ if(strcmp(m_data,s.m_data)>0) return true; return false;}bool String::operator<=(String &s){ if(strcmp(m_data,s.m_data)>=0) return true; return false;}bool String::operator<(String &s){ if(strcmp(m_data,s.m_data)<0) return true; return false;}bool String::operator>=(String &s){ if(strcmp(m_data,s.m_data)<=0) return true; return false;}char& String::operator[](int index){// char*p= m_data;// return *(p+index); return m_data[index];}#endif
再下面是測試程式:
#include "operator.h"int main(){ String s("s"); String s1("s"); String s2; //String s3; //s2 = s+s1; //s+=s1; //cout<<"s+=s1="<<s<<endl; cout<<"s[2] = "<<s[0]<<endl;// if(s == s1)// cout<<1<<endl;// if(s != s1)// cout<<0<<endl;// if(s > s1)// cout<<"s>s1"<<endl;// if(s >= s1)// cout<<"s>=s1"<<endl;// if(s < s1)// cout<<"s<s1"<<endl;// if(s <=s1)// cout<<"s<=s1"<<endl; //cin>>s3; //cout<<"s3="<<s3<<endl;//請分開測試 return 0;}
輸入S3以後不知道為什麼就成了大寫
[c++]String字串類的運算子多載