編碼實現字符串類CNString,該類有默認構造函數、類的拷貝函數、類的析構函數及運算符重載,需實現以下“=”運算符、“+”運算、“[]”運算符、“<”運算符及“>”運算符及“==”運算符
以下為各個運算符的運算效果的詳細說明:
a) 字符串“=”重載運算符
CNStringstr1("abc ");
CNString str2 = str1;
b) 字符串“+”運算
CNStringstr1("abc");
CNStringstr2("efg ");
str1 = str1 + str2;
c) 字符串“[]”運算
CNString nstring1("abc");
cout<< nstring1[0] ;// 則屏幕顯示a
cout<< nstring1[2] ; // 則屏幕顯示c
d) “<”運算符
CNStringstr1("abc");
CNStringstr2("efg");
if (str1 <str2 ){
cout<<“str1<str2”<<endl;
}
e) “>”運算符
CNStringstr1("abc");
CNStringstr2("efg");
if (str1 >str2 ){
cout<<“str1>str2”<<endl;
}
f) “==”運算符
CNStringstr1("abc");
CNStringstr2("efg");
if (str1 == str2){
cout<<“str1==str2”<<endl;
}
代碼實現:
#include<iostream> #include<string.h> using namespace std; class CNString { private: char *str_F; public: CNString(){str_F=NULL;};//默認構造函數 CNString(char *str);//有參構造函數 CNString(const CNString &other);//類的拷貝函數 ~CNString();//類的析構函數 CNString &operator=(const CNString &obj);//"="號重載 CNString &operator+(const CNString &obj);//"+"號重載 char& operator[](int i);//"[]"號重載 bool operator<(const CNString &obj);//"<"號重載 bool operator>(const CNString &obj);//">"號重載 bool operator==(const CNString &obj);//"=="號重載 void print()//打印str_F的結果 { cout<<str_F<<endl; } }; CNString::CNString(char *str) { str_F = new char(strlen(str)+1); if(str_F!=0) strcpy(str_F,str); } CNString::CNString(const CNString &obj) { str_F = new char(strlen(obj.str_F)+1); if(str_F!=0) strcpy(str_F,obj.str_F); } CNString::~CNString() { delete []str_F; } CNString & CNString::operator=(const CNString &obj) { char * tem=new char(strlen(obj.str_F)+1); strcpy(tem,obj.str_F); str_F=tem; delete[]tem; return *this; } CNString & CNString::operator+(const CNString &obj) { strcat(str_F,obj.str_F); return *this; } char &CNString::operator[](int i) { return str_F[i]; } bool CNString::operator<(const CNString &obj) { int c = strcmp(str_F,obj.str_F); if(c<0) return true; else return false; } bool CNString::operator>(const CNString &obj) { int c = strcmp(str_F,obj.str_F); if(c>0) return true; else return false; } bool CNString::operator==(const CNString &obj) { int c = strcmp(str_F,obj.str_F); if(c==0) return true; else return false; } int main() { CNString str1("abc "); CNString str2("edf"); CNString str3; cout<<"實現運算符+和=重載后:"<<endl; str3 = str1 + str2; str3.print(); cout<<"實現運算符[]重載后:"<<endl; CNString nstring1("abc"); cout<<nstring1[0]<<endl; cout<<"實現運算符'<' '>' '=='重載后:"<<endl; if (str1 <str2 ) { cout<<"str1<str2"<<endl; } if (str1 >str2 ) { cout<<"str1>str2"<<endl; } if(str1==str2) { cout<<"str1==str2"<<endl; } return 0; }
實現效果圖: