C、C++语言面试题 2007-07-15 18:57 1.已知 strcpy 函数的原型是: char *strcpy(char *strDest, const char *strSrc); 其中 strDest 是目的字符串,strSrc 是源字符串。不调用 C++/C 的字符串库函数,请编写函数 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++) != ‘\0’) ; return tempptr ; } 2.已知类 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(const char *str) { if ( str == NULL ) //strlen 在参数为 NULL 时会抛异常才会有这步判断 { m_data = new char[1] ; m_data[0] = '\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.简答 3.1 头文件中的ifndef/define/endif 干什么用? 答:防止该头文件被重复引用。 3.2#include 和#include “filename.h” 有什么区别? 答:对于#include ,编译器从标准库路径开始搜索 filename.h 对于#include “filename.h”,编译器从用户的工作路径开始搜索 filename.h 3.3 在 C++ 程序中调用被C 编译器编译后的函数,为什么要加 extern “C”? 答:C++语言支持函数重载,C 语言不支持函数重载。函数被C++编译后在库中的名字与 C 语言的不同。假设某个...