C 中字串類String的一些函式

2021-08-09 22:55:13 字數 2561 閱讀 8816

c++

字串

string

的一些函式原型

class string

c++

編譯器會自動為乙個類產生四個預設的函式,如:無參的建構函式,拷貝建構函式,析構函式,賦值函式。

字串拷貝函式

strcpy

的原型:

char *strcpy(char *strdest, const char *strsrc)

return strtmp;

}

析構函式

string::~string(void)

建構函式

string::string(const char *str)else

}

預設的拷貝建構函式

,預設的賦值函式都是採用「位拷貝」,而非「值拷貝」的方式實現,如果類中含有指標變數,這兩個函式都會出錯

,因為「位拷貝」拷貝的是位址(是

memorycopy

),實際需要的可能是拷貝內容的「值拷貝」(

strcpy

)。

string

型別來說,把

str2

賦值給str1

,「位拷貝」意味著執行

str1.m_data=str2.m_data;

這裡會有三個問題:

1

)str1.m_data

原有的記憶體沒有被釋放,造成記憶體洩露;2)

str1.m_data

和str2.m_data

指向同一塊記憶體,所以乙個變動會影響另乙個;

3)在物件被析構時,

m_data

會被釋放兩次。

拷貝建構函式是在物件被建立時呼叫的

,而賦值函式只能被已經存在了的物件呼叫,如:

string str1(「abc」);

string str2(「123」);

string str3 = str1;//這裡呼叫了拷貝建構函式,跟string str3(str1);寫法相同。

str3 = str2;//這裡呼叫了賦值函式

拷貝建構函式

string::string(const string &other)
過載的賦值函式

operate=

的原型:

string & string::operate=(const string &other)

賦值函式的返回值型別是引用,返回

*this

的引用,不需要拷貝過程;如果用「值傳遞」,也就是說如果返回型別是值型別,功能沒有問題

,但是因為

return

語句要把

*this

拷貝到儲存返回值的外部儲存單元中

,增加了不必要的開銷,降低了賦值函式的效率。

過載

string

的相加函式

operate+

的實現:

string operate+(const string &s1, const string &s2)

相加函式的返回值型別是值型別,如果使用「引用傳遞」,也就是返回值改為引用型別,功能就無法實現了,因為函式返回的是乙個指向區域性物件變數

temp

的引用,函式內的區域性變數的儲存單元是在棧空間的

由於

temp

在函式結束時被自動銷毀,所以導致返回的引用無效了。

C 中的字串類(string類)

1.字串搜尋 string s abc科學 int i s.indexof 科 注意 1 索引從0開始,如果沒有找到則返回值為 1 2 c 中,ascii和漢字都是用2位元組表示 2.字串比較 string s1 abc string s2 abc int n string.compare s1,s...

字串的一些常用方法 string

字串 字串 由0個或多個字元組成,被成對的英文單引號或雙引號包含起來的。字元編碼 每乙個字元在計算機儲存的編號。計算機會儲存有一套或幾套用於標註編號與字元對應關係的字典。字符集 計算機儲存單位 位 bit 0 1能存2個字 位元組 byte 8bit可存256個不同的字。kb 1kb 1024byt...

string 的一些字串操作函式

1.find查詢函式 函式原型 size t find const string str,size t pos 0 const size t find const char s,size t pos,size t n const size t find const char s,size t pos...