五、編寫strcpy函數(10分)
已知strcpy函數的原型是
char strcpy(char strDest, const char strSrc);
其中strDest是目的字符串,strSrc是源字符串。
(1)不調用C++/C的字符串庫函數,請編寫函數 strcpy
char strcpy(char strDest, const char strSrc);
{
assert((strDest!=NULL) && (strSrc !=NULL)); // 2分
char address = strDest; // 2分
while( (strDest++ = strSrc++) != ‘\0’ ) // 2分
NULL ;
return address ; // 2分
}
(2)strcpy能把strSrc的內容復制到strDest,為什么還要char 類型的返回值?
答:為了實現鏈式表達式。 // 2分
例如 int length = strlen( strcpy( strDest, “hello world”) );
六、編寫類String的構造函數、析構函數和賦值函數(25分)
已知類String的原型為:
class String
{
public:
String(const char str = NULL); // 普通構造函數
String(const String &other); // 拷貝構造函數
~ String(void); // 析構函數
String & operate =(const String &other); // 賦值函數
private:
char m_data; // 用于保存字符串
};
請編寫String的上述4個函數。
標準答案:
// String的析構函數
String::~String(void) // 3分
{
delete [] m_data;
// 由于m_data是內部數據類型,也可以寫成 delete m_data;
}
// String的普通構造函數
String::String(const char str) // 6分
{
if(str==NULL)
{
m_data = new char; // 若能加 NULL 判斷則更好
m_data = ‘\0’;
}
else
{
int length = strlen(str);
m_data = new char[length+1]; // 若能加 NULL 判斷則更好
strcpy(m_data, str);
}
}
// 拷貝構造函數
String::String(const String &other) // 3分
{
int length = strlen(other.m_data);
m_data = new char[length+1]; // 若能加 NULL 判斷則更好
strcpy(m_data, other.m_data);
}
// 賦值函數
String & String::operate =(const String &other) // 13分
{
// (1) 檢查自賦值 // 4分
if(this == &other)
return this;
// (2) 釋放原有的內存資源 // 3分
delete [] m_data;
// (3)分配新的內存資源,并復制內容 // 3分
int length = strlen(other.m_data);
m_data = new char[length+1]; // 若能加 NULL 判斷則更好
strcpy(m_data, other.m_data);
// (4)返回本對象的引用 // 3分
2020年河北新聞網兩學一做
時間:2023-09-18 07:0:242020年河北新聞網兩學一做
時間:2023-09-15 11:0:59兩學一做學習教育知
時間:2023-09-21 06:0:302020年開展兩學一做學習教
時間:2023-09-19 21:0:30
五星電器經典筆試題和面試題答案2023-09-16 12:44:29
箭牌2019校招筆試題和面試題答案目2023-09-19 01:13:31
陜西國際商貿學院在重慶高考專業(yè)招生計劃(人數+代碼)2025-05-22 10:38:12
安徽建筑大學和新余學院哪個好 分數線排名對比2025-05-22 10:36:54
襄陽職業(yè)技術學院廣西錄取分數線及招生人數 附-2020最低位次排名2025-05-22 10:35:29
長江大學和新疆師范大學哪個好 分數線排名對比2025-05-22 10:34:16
錦州師范高等?茖W校在遼寧高考專業(yè)招生計劃(人數+代碼)2025-05-22 10:32:49
山東高考排名在17550的考生能報什么大學(原創(chuàng))2025-05-22 10:31:33
廣州華立學院的英語專業(yè)分數線(附2020-最低分排名怎么樣)2025-05-22 10:30:14
蘭州石化職業(yè)技術大學的理化測試與質檢技術專業(yè)分數線(附2020-最低分排名怎么樣)2025-05-22 10:29:06
泉州師范學院和亳州學院哪個好 分數線排名對比2025-05-22 10:27:53
貴州醫(yī)科大學在江西高考專業(yè)招生計劃(人數+代碼)2025-05-22 10:26:23
東莞城市學院和西安工商學院哪個好 分數線排名對比2025-05-22 10:24:51
山東海事職業(yè)學院的水路運輸安全管理專業(yè)分數線(附2020-最低分排名怎么樣)2025-05-22 10:23:44 


