c++操作符重载有点儿好耍...
时间:2010-08-10 来源:xianzq888
都发了好久的贴要认真学习C++咯,但是由于喃项目原因,没有看书,现在这个托我做项目的娃儿叫我仿照另一个东西做,我那个心情哦.最讨厌这些只关心介面,只关心看到的人咯,什么都不知道.其实他叫我仿照的那个就是垃圾.等他来找我我也不愿意再做了,三天两头的这样功能那样功能的..还不如多看看书...
今天这个操作符重载还多有意思的..但是不知道用C该如何实现呢?如果要实现一定要写不少代码..我那个汗哟..- -!!
帖出来耍耍...再往下看....记录下我学习的踪迹...嘿嘿....
示例1:
#include <iostream> #include <string.h> using namespace std; class String { public: String(void) { sSize=0; cstr=NULL; } String(const char *str) { sSize=strlen(str); cstr=new char[sSize+1]; strcpy(cstr,str); } char &operator[](int len) { if(len>=0&&len<sSize) return cstr[len]; } String &operator=(const String &str) { if(this!=&str) { delete []cstr; sSize=str.sSize; if(!str.cstr) { sSize=0; } else { cstr=new char[str.sSize+1]; strcpy(cstr,str.cstr); } } return *this; } ~String() { delete []cstr; } private: int sSize; char *cstr; protected: }; int main(int argc, char *argv[]) { String str1,str2("123456789"); str1=str2; cout<<str1[8]<<'\n'<<str2[0]<<endl; return 0; }
示例2:
#include <iostream> #include <string.h> using namespace std; class String { public: String(void) { sSize=0; cstr=NULL; } String(const char *str) { sSize=strlen(str); cstr=new char[sSize+1]; strcpy(cstr,str); } char &operator[](int len) { if(len>=0&&len<sSize) return cstr[len]; } String &operator=(const String &str) { if(this!=&str) { delete []cstr; sSize=str.sSize; if(!str.cstr) { sSize=0; } else { cstr=new char[str.sSize+1]; strcpy(cstr,str.cstr); } } return *this; } String &operator+(const String &str) { char *temp=NULL; temp=new char[sSize+str.sSize+1]; strcpy(temp,cstr); strcat(temp,str.cstr); delete []cstr; cstr=temp; return *this; } char *GetString(void) { return cstr; } ~String() { delete []cstr; } private: int sSize; char *cstr; protected: }; int main(int argc, char *argv[]) { String str1("000"),str2("123456789"); str1+str2; cout<<str1.GetString()<<endl; return 0; }