c/c++經典面試試題及標準答案(一)

c/c++經典面試試題及標準答案
下面的問題我想大部分c/c++ 程序員 都遇見過,原文出自林銳博士的《高質量c/c++編程》,這本書非常好,我當初面試時從中受益頗多,不知道大家看過沒有,如果沒有看過,我特別推薦一下。 
一、請填寫BOOL , float,指針變量零值比較的 if 語句。(10分)
 
請寫出 BOOL flag零值比較的 if語句。(3分)
標準答案:
    if ( flag )
    if ( !flag )
如下寫法均屬不良風格,不得分。
    if (flag == TRUE)  
    if (flag == 1 )    
    if (flag == FALSE) 
        if (flag == 0)
請寫出 float x 零值比較的 if語句。(4分)
標準答案示例:
const float EPSINON = 0.00001;
if ((x >= - EPSINON) && (x <= EPSINON)
不可將浮點變量用“==”=”與數字比較,應該設法轉化成“>=”“<=”此類形式。
如下是錯誤的寫法,不得分。
    if (x == 0.0)  
    if (x != 0.0)      
請寫出 char *p 零值比較的 if語句。(3分)
標準答案:
    if (p == NULL)
    if (p != NULL)
如下寫法均屬不良風格,不得分。
    if (p == 0)
    if (p != 0)    
    if (p) 
        if (!)     
二、以下爲Windows NT下的32C++程序,請計算sizeof的值(10分)
 char str[] = “Hello” ;
 char   *p = str ;
int     n = 10;
請計算
sizeof (str ) = 6   2分)
sizeof ( p ) =   4   2分)
sizeof ( n ) =   4   2分)
 
void Func ( char str[100])
{
請計算
sizeof( str ) =   4     2分)
}
void *p = malloc( 100 );
請計算
sizeof ( p ) = 4      2分)
 
 三、簡答題(25分)
 
1、頭文件中的 ifndef/define/endif幹什麼用?(5分)
答:防止該頭文件被重複引用。
 
2#include <filename.h>   #include “filename.h”有什麼區別?(5分)
答:對於#include <filename.h>,編譯器從標準庫路徑開始搜索 filename.h
    對於#include “filename.h”,編譯器從用戶的工作路徑開始搜索 filename.h
 
3const有什麼用途?(請至少說明兩種)(5分)
答:(1)可以定義 const常量
2const可以修飾函數的參數、返回值,甚至函數的定義體。被const修飾的東西都受到強制保護,可以預防意外的變動,能提高程序的健壯性。
 
4、在C++程序中調用被 C編譯器編譯後的函數,爲什麼要加 extern “C”5分)
答:C++語言支持函數重載,C語言不支持函數重載。函數被C++編譯後在庫中的名字與C語言的不同。假設某個函數的原型爲:void foo(int x, int y);
該函數被C編譯器編譯後在庫中的名字爲_foo,而C++編譯器則會產生像_foo_int_int之類的名字。
C++提供了C連接交換指定符號extern“C”來解決名字匹配問題。
 
5、請簡述以下兩個for循環的優缺點(5分)
 
for (i=0; i<N; i++)
{
if (condition)
    DoSomething();
else
    DoOtherthing();
}
優點:程序簡潔
 
缺點:多執行了N-1次邏輯判斷,並且打斷了循環流水線作業,使得編譯器不能對循環進行優化處理,降低了效率。
if (condition)
{
for (i=0; i<N; i++)
    DoSomething();
}
else
{
    for (i=0; i<N; i++)
    DoOtherthing();
}
優點:循環的效率高
 
缺點:程序不簡潔
四、有關內存的思考題(每小題5分,共20分)
void GetMemory(char *p)
{
p = (char *)malloc(100);
}
void Test(void)
{
char *str = NULL;
GetMemory(str);  
strcpy(str, "hello world");
printf(str);
}
 
請問運行Test函數會有什麼樣的結果?
答:程序崩潰。
因爲GetMemory並不能傳遞動態內存,
Test函數中的 str一直都是 NULL
strcpy(str, "hello world");將使程序崩潰。
 
char *GetMemory(void)
{  
char p[] = "hello world";
return p;
}
void Test(void)
{
char *str = NULL;
str = GetMemory();   
printf(str);
}
 
請問運行Test函數會有什麼樣的結果?
答:可能是亂碼。
因爲GetMemory返回的是指向棧內存的指針,該指針的地址不是 NULL,但其原先的內容已經被清除,新內容不可知。
void GetMemory2(char **p, int num)
{
*p = (char *)malloc(num);
}
void Test(void)
{
char *str = NULL;
GetMemory(&str, 100);
strcpy(str, "hello");  
printf(str);   
}
請問運行Test函數會有什麼樣的結果?
答:
1)能夠輸出hello
2)內存泄漏
void Test(void)
{
char *str = (char *) malloc(100);
    strcpy(str, “hello”);
    free(str);    
    if(str != NULL)
    {
     strcpy(str, “world”);
printf(str);
}
}
請問運行Test函數會有什麼樣的結果?
答:篡改動態內存區的內容,後果難以預料,非常危險。
因爲free(str);之後,str成爲野指針,
if(str != NULL)語句不起作用。
 
五、編寫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
}
 
2strcpy能把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[1];    // 若能加 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
       return *this;
}  
附:
1.帶引用計數的String類的實現(摘自More Effective C++):
template<class T>                       // template class for smart 
class RCPtr {                                // pointers-to-T objects; T 
public:                                            // must inherit from RCObject 
  RCPtr(T* realPtr = 0); 
  RCPtr(const RCPtr& rhs); 
  ~RCPtr(); 

  RCPtr& operator=(const RCPtr& rhs); 
  T* operator->() const; 
  T& operator*() const; 
private: 
  T *pointee; 
  void init(); 
}; 

class RCObject {                       // base class for reference- 
public:                                          // counted objects 
  void addReference(); 
  void removeReference(); 
  void markUnshareable(); 
  bool isShareable() const; 
  bool isShared() const; 
protected: 
  RCObject(); 
  RCObject(const RCObject& rhs); 
  RCObject& operator=(const RCObject& rhs); 
  virtual ~RCObject() = 0; 
private: 
  int refCount; 
  bool shareable; 
}; 

class String {                           // class to be used by 
public:                                       // application developers 
  String(const char *value = ""); 
  const char& operator[](int index) const; 
  char& operator[](int index); 
private: 
  // class representing string values 
  struct StringValue: public RCObject {
    char *data; 
    StringValue(const char *initValue); 
    StringValue(const StringValue& rhs); 
    void init(const char *initValue); 
    ~StringValue(); 
  }; 
  RCPtr<StringValue> value; 
}; 

RCPtr的實現: 
template<class T> 
void RCPtr<T>::init() 

  if (pointee == 0) return; 
  if (pointee->isShareable() == false) { 
    pointee = new T(*pointee); 
  } 
  pointee->addReference(); 


template<class T> 
RCPtr<T>::RCPtr(T* realPtr) 
: pointee(realPtr) 
{ init(); } 

template<class T> 
RCPtr<T>::RCPtr(const RCPtr& rhs) 
: pointee(rhs.pointee) 
{ init(); } 

template<class T> 
RCPtr<T>::~RCPtr() 
{ if (pointee)pointee->removeReference(); } 

template<class T> 
RCPtr<T>& RCPtr<T>::operator=(const RCPtr& rhs) 

  if (pointee != rhs.pointee) { 
    if (pointee) pointee->removeReference(); 
    pointee = rhs.pointee; 
    init(); 
  } 
return *this; 


template<class T> 
T* RCPtr<T>::operator->() const { return pointee; } 

template<class T> 
T& RCPtr<T>::operator*() const { return *pointee; } 

RCObject 的實現: 
RCObject::RCObject() 
: refCount(0), shareable(true) {} 

RCObject::RCObject(const RCObject&) 
: refCount(0), shareable(true) {} 

RCObject& RCObject::operator=(const RCObject&) 
{ return *this; } 

RCObject::~RCObject() {} 

void RCObject::addReference() { ++refCount; } 

void RCObject::removeReference() 
{ if (--refCount == 0) delete this; } 

void RCObject::markUnshareable() 
{ shareable = false; } 

bool RCObject::isShareable() const 
{ return shareable; } 

bool RCObject::isShared() const 
{ return refCount > 1; } 

String::StringValue 的實現: 
void String::StringValue::init(const char *initValue) 

  data = new char[strlen(initValue) + 1]; 
  strcpy(data, initValue); 


String::StringValue::StringValue(const char *initValue) 
{ init(initValue); } 

String::StringValue::StringValue(const StringValue& rhs) 
{ init(rhs.data); } 

String::StringValue::~StringValue() 
{ delete [] data; } 

最後,歸結到 String,它的實現是: 
String::String(const char *initValue) 
: value(new StringValue(initValue)) {} 

const char& String::operator[](int index) const 
{ return value->data[index]; } 

char& String::operator[](int index) 

  if (value->isShared()) { 
    value = new StringValue(value->data); 
  } 
  value->markUnshareable(); 
  return value->data[index]; 


2.c++中智能指針auto_ptr的實現(摘自More Effective C++):
template<class T> 
class auto_ptr { 
public: 
  explicit auto_ptr(T *p = 0): pointee(p) {} 

  template<class U> 
  auto_ptr(auto_ptr<U>& rhs): pointee(rhs.release()) {}

  ~auto_ptr() { delete pointee; } 

  template<class U> 
  auto_ptr<T>& operator=(auto_ptr<U>& rhs) 
  { 
    if (this != &rhs) reset(rhs.release()); 
    return *this; 
  } 

  T& operator*() const { return *pointee; } 
  T* operator->() const { return pointee; } 
  T* get() const { return pointee; } 

  T* release() 
  { 
 T *oldPointee = pointee; 
    pointee = 0; 
    return oldPointee; 
  } 

  void reset(T *p = 0) 
  { 
    if (pointee != p) { 
      delete pointee; 
      pointee = p; 
    } 
  } 

  private: 
    T *pointee; 

  template<class U> 
friend class auto_ptr<U>; 
  }; 
發佈了9 篇原創文章 · 獲贊 0 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章