在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; }
原文地址:http://blog.csdn.net/cherry_ermao/article/details/46399857