當(dāng)前位置:高考知識網(wǎng) > 招聘筆試題 > 正文
五、編寫strcpy函數(shù)(10分)
已知strcpy函數(shù)的原型是
char *strcpy(char *strdest, const char *strsrc);
其中strdest是目的字符串,strsrc是源字符串。
(1)不調(diào)用c++/c的字符串庫函數(shù),請編寫函數(shù) 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的內(nèi)容復(fù)制到strdest,為什么還要char * 類型的返回值?
答:為了實(shí)現(xiàn)鏈?zhǔn)奖磉_(dá)式。 // 2分
例如 int length = strlen( strcpy( strdest, “hello world”) );
六、編寫類string的構(gòu)造函數(shù)、析構(gòu)函數(shù)和賦值函數(shù)(25分)
已知類string的原型為:
class string
{
public:
string(const char *str = null); // 普通構(gòu)造函數(shù)
string(const string other); // 拷貝構(gòu)造函數(shù)
~ string(void); // 析構(gòu)函數(shù)
string operate =(const string &other); // 賦值函數(shù)
private:
char *m_data; // 用于保存字符串
};
請編寫string的上述4個(gè)函數(shù)。
標(biāo)準(zhǔn)答案:
// string的析構(gòu)函數(shù)
string::~string(void) // 3分
{
delete [] m_data;
// 由于m_data是內(nèi)部數(shù)據(jù)類型,也可以寫成 delete m_data;
}
// string的普通構(gòu)造函數(shù)
string::string(const char *str) // 6分
{
if(strnull)
{
m_data = new char[1]; // 若能加 null 判斷則更好
*m_data = ‘\0’;
}
else
{
int length = strlen(str);
m_data = new char[length+1]; // 若能加 null 判斷則更好
strcpy(m_data, str);
}
}
// 拷貝構(gòu)造函數(shù)
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);
}
// 賦值函數(shù)
string string:perate =(const string other) // 13分
{
// (1) 檢查自賦值 // 4分
if(this other)
return *this;
// (2) 釋放原有的內(nèi)存資源 // 3分
delete [] m_data;
// (3)分配新的內(nèi)存資源,并復(fù)制內(nèi)容 // 3分
int length = strlen(other.m_data);
m_data = new char[length+1]; // 若能加 null 判斷則更好
strcpy(m_data, other.m_data);
// (4)返回本對象的引用 // 3分
return *this;
}
金山職業(yè)技術(shù)學(xué)院對比四川汽車職業(yè)技術(shù)學(xué)院哪個(gè)好 附分..
時(shí)間:2025-05-22 09:08:12成都銀杏酒店管理學(xué)院在重慶高考招生計(jì)劃人數(shù)和專業(yè)代..
時(shí)間:2025-05-22 09:05:01四川上山東理工大學(xué)多少分 分?jǐn)?shù)線及排名
時(shí)間:2025-05-22 09:01:18江西高考理科533分排名多少 排名多少位次
時(shí)間:2025-05-22 08:57:21大連東軟信息學(xué)院對比甘肅民族師范學(xué)院哪個(gè)好 附分?jǐn)?shù)線..
時(shí)間:2025-05-22 08:53:39廣東高考455至460分左右物理可以上什么大學(xué)
時(shí)間:2025-05-22 08:49:52