1、代碼如下: 注意:形參加上const修飾符,函數(shù)體里面判斷參數(shù)是否為NULL,引用不能為空等。 復制操作符應該判斷是否是自賦值。 重載輸入操作符時,要注意給data分配足夠的空間,現(xiàn)在還沒有想到太好的辦法,用的是臨時變量,這里一直不是很明白C++中的(string s; cin>>s;)到底最大可以讀取多少個字符,其原理又是怎么實現(xiàn)的呢。 友元函數(shù)有時候編譯器會有bug,解決方法如下:事先聲明類和友元函數(shù)(在類外面不能用friend 關(guān)鍵字) class String; ostream& operator<<(ostream& out,const String& s); stream& operator>>(istream& in,const String& s); bool operator<(const String& s1,const String &s2); - #include "stdafx.h"
- #include <iostream.h>
- #include <string.h>
-
- class String
- {
- public:
- String();
- String(const char *str);
- String(const String &s);
- ~String();
- String& operator=(const String &str);
- friend ostream& operator<<(ostream& out,const String& s);
- friend istream& operator>>(istream& in,String& s);
- friend bool operator<(const String& s1,const String &s2);
- char& operator[](int pos)
- {
- cout<<"index operator"<<endl;
- int len=strlen(data);
- if (pos>=len)
- {
- return data[len-1];
- }
- else
- {
- return data[pos];
- }
- }
-
- private:
- char *data;
- };
-
- //默認構(gòu)造函數(shù)
- String::String()
- {
- cout<<"default constructor"<<endl;
- data=new char[1];
- *data='\0';
- }
-
- //帶參數(shù)構(gòu)造函數(shù)
- String::String(const char *str)
- {
- cout<<"parameter constructor"<<endl;
- if (str==NULL)
- {
- data=new char[1];
- *data='\0';
- }
- else
- {
- int len=strlen(str);
- data=new char[len+1];
- strcpy(data,str);
- }
- }
-
-
- //復制構(gòu)造函數(shù)
- String::String(const String &str)
- {
- cout<<"copy constructor"<<endl;
- int len=strlen(str.data);
- data=new char[len+1];
- strcpy(data,str.data);
- }
-
- //析構(gòu)函數(shù)
- String::~String()
- {
- cout<<"destructor"<<endl;
- delete[] data;
- }
-
- //賦值操作符
- String& String::operator=(const String &str)
- {
- cout<<"assign operator"<<endl;
- if (this!=&str)
- {
- int len=strlen(str.data);
- delete[] data;
- data=new char[len+1];
- strcpy(data,str.data);
- }
-
- return *this;
- }
-
- //輸出操作符
- ostream& operator<<(ostream& out,const String& s)
- {
- cout<<"cout operator"<<endl;
- out<<s.data<<endl;
- return out;
- }
-
- //輸入操作符
- istream& operator>>(istream& in,String& s)
- {
- cout<<"cin operator"<<endl;
- //這個地方很傷神,目前沒有想到很好的辦法,只能先用中間變量來獲取輸入的長度,然后釋放中間變量
- char *sTemp=new char[1000];
- in>>sTemp;
-
- delete[] s.data;
- int len=strlen(sTemp);
- s.data=new char[len+1];
- strcpy(s.data,sTemp);
-
- delete[] sTemp;
- return in;
- }
-
- //比較操作符
- bool operator<(const String& s1,const String &s2)
- {
- cout<<"compare operator"<<endl;
- if (strcmp(s1.data,s2.data)<0)
- {
- return 1;
- }
- return 0;
- }
-
-
-
- void main()
- {
- String s1; //default constructor
- String s2("12345"); //parameter constructor
- String s3=s2; //copy constructor
- s1=s2; //assign operator
-
- cin>>s1; //輸入操作符
- cout<<s1; //輸出操作符
-
- cout<<(s1<s2)<<endl; //比較操作符
-
- cout<<(s1[5])<<endl; //獲取字符
-
- //destructor destructor destructor
- }
|