常見(jiàn)筆試/面試題目(一) □daibaobao 發(fā)表于 2005-12-9 15:49:00
1.已知strcpy 函數(shù)的原型是:
char *strcpy(char *strDest, const char *strSrc);
其中strDest 是目的字符串,strSrc 是源字符串。不調(diào)用C++/C 的字符串庫(kù)函數(shù),請(qǐng)編寫(xiě)函數(shù) strcpy
答案:
char *strcpy(char *strDest, const char *strSrc)
{
if ( strDest == NULL || strSrc == NULL)
return NULL ;
if ( strDest == strSrc)
return strDest ;
char *tempptr = strDest ;
while( (*strDest++ = *strSrc++) != ‘’)
;
return tempptr ;
}
2.已知類(lèi)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; // 用于保存字符串
};
請(qǐng)編寫(xiě)String 的上述4 個(gè)函數(shù)。
答案:
String::String(const char *str)
{
if ( str == NULL ) //strlen在參數(shù)為NULL時(shí)會(huì)拋異常才會(huì)有這步判斷
{
m_data = new char[1] ;
m_data[0] = ‘‘ ;
}
else
{
m_data = new char[strlen(str) + 1];
strcpy(m_data,str);
}
}
String::String(const String &other)
{
m_data = new char[strlen(other.m_data) + 1];
strcpy(m_data,other.m_data);
}
String & String::operator =(const String &other)
{
if ( this == &other)
return *this ;
delete []m_data;
m_data = new char[strlen(other.m_data) + 1];
strcpy(m_data,other.m_data);
return *this ;
}
String::~ String(void)
{
delete []m_data ;
}
3.簡(jiǎn)答
3.1 頭文件中的ifndef/define/endif 干什么用?
答:防止該頭文件被重復(fù)引用。
3.2#i nclude 和#i nclude “filename.h” 有什么區(qū)別?
答:對(duì)于#i nclude ,編譯器從標(biāo)準(zhǔn)庫(kù)路徑開(kāi)始搜索filename.h
對(duì)于#i nclude “filename.h”,編譯器從用戶的工作路徑開(kāi)始搜索filename.h