C 字串中運算子的過載問題

2021-10-10 04:06:20 字數 2645 閱讀 7030

運算子的過載:

運算子的過載實際是一種特殊的函式過載,必須定義乙個函式,並告訴c++編譯器,當遇到該過載的運算子時呼叫此函式。這個函式叫做運算子過載函式,通常為類的成員函式。

定義運算子過載函式的一般格式:

返回值型別 類名::operator過載的運算子(參數列)

在字串中,運算子的過載問題在於字串和字串之間進行計算。

首先我們定義乙個字串的類,並為其寫出建構函式、拷貝建構函式,析構函式、列印字串函式。

class

string

else

}public

:string

(const

char

*p =

null

)//建構函式

else

}string

(const string &s)

//拷貝建構函式

~string()

//析構函式

void

printstring()

//列印字串函式

};

若沒有顯示地定義實現這些函式,編譯器也會為類加上預設的這些函式,這叫做預設函式。

關於字串類的建立中的一些解釋:

在建構函式中

string

(const

char

*p =

null

)//建構函式

else

}

引數預設值為null,若字串為空,則為其建立一位元組空間,,並在其中輸入』\0』。這樣就避免了字串為空造成的問題。

在拷貝建構函式中

string

(const string &s)

//拷貝建構函式

首先定義n來獲取原字串的長度,然後動態開闢乙個長度為n的新字串,通過strcpy函式將原字串中的內容拷貝的新字串中。這種拷貝建構函式也叫做深拷貝。

這樣避免了兩個字串指向同一空間造成二次釋放問題。

1、 『=』 運算子過載

// void operator=(string * const this,const string &s)

string &

operator=(

const string &s)

return

*this

;}

首先判斷是避免自己給自己賦值的情況。之後釋放 『=』 左邊字串指標指向的空間,定義n用來計算 『=』 右邊字串長度,給左邊字串開闢乙個和右邊大小相同空間,最後將右邊字串的內容拷貝到左邊字串中。

這樣避免了兩個字串指向同一空間造成二次釋放問題。

關於函式名的說明

函式返回型別是string,且是 『&』 引用。這樣可以進行連續賦值,例如s3=s2=s1,先將s1賦值給s2,再將s2賦值給s3(其函式形式:

s3.operator=(s2.operator=(s1))

operator=(&s3,operator=(&s2,s1))

)使用引用返回,可以避免產生臨時量。(注:物件生存週期不受函式影響,就可以使用引用返回)

2、 『+』 運算子過載

// string & operator+(const string * const this,const string &s)

string operator+(

const string &s)

const

使用值返回,是因為產生的臨時量,臨時量在函式結束是已經被析構了,所以不能使用引用返回。

在private中加入乙個建構函式如下(在引數中加乙個int,是為了和public中的建構函式區別)。

string

(char

*p,int

)else

}

這樣就解決了函式中記憶體洩漏問題。

補充:記憶體洩漏

(1)開闢的空間丟失位址。

(2)堆空間被用盡了。

3、 『+』 運算子過載(物件和字串)

// string operator+(const string * const this,const char *sp);

string operator+(

const

char

*sp)

const

4、 『+』 運算子過載(字串和物件)

string operator+(

const

char

*sp,

const string &s)

注:因為類的成員預設有引數this指標,所以該函式要作為全域性函式。

5、 『+』 運算子過載(下標運算子過載)

char

&operator

(int index)

const

char

&operator

(int index)

const

//常引用

字串類中的運算子過載

ifndef string h define string h include using namespace std class string endif include string.h include include include using namespace std string str...

字串類 運算子過載

mystring.h define crt secure no warnings includeusing namespace std 在這裡定義類只寫類的函式名,不寫類的函式體 c中沒有字串,字串 c風格字串 空串 class mystring const char c str2 int leng...

c String字串類的運算子過載

在c 中有乙個新定義的型別string,可以不用那麼麻煩的操作字串,並且一些高階的運算子過載讓她的使用更加便捷 下面是string類的定義和成員函式的定義 ifndef operator operator h define operator operator h include includeusi...