天天看點

C++資料結構筆試題

一:

已知類String的原型為:

class String

{

 public:

     String(const char *str = NULL);            //普通構造函數

     String(const String ©);                //拷貝構造函數

     ~String(void);                             //析構函數

     String & operator = (const String ©);  //指派構造函數

 private:

     char * m_data;                             //用于儲存字元串

};

請編寫String的上述4個函數。

答案:

版本1

// String 的析構函數

String::~String(void) // 3 分

  if(m_data)

    delete [] m_data;

// 由于m_data 是内部資料類型,也可以寫成delete m_data;

}

String::String(const char *str)

 if(str==NULL)

 m_data = new char[1]; // 若能加NULL 判斷則更好

 *m_data = ‘{post.content}’;

 }

else

 {

 int length = strlen(str);

 m_data = new char[length+1]; // 若能加NULL 判斷則更好

 strcpy(m_data, str);

// 拷貝構造函數

String::String(const String &other)

 int length = strlen(other.m_data);

 strcpy(m_data, other.m_data);

// 指派函數

String & String:operate =(const String &other)

// (1) 檢查自指派

if(this == &other)

return *this;

// (2) 釋放原有的記憶體資源

delete [] m_data;

// (3)配置設定新的記憶體資源,并複制内容

m_data = new char[length+1]; // 若能加NULL 判斷則更好

// (4)傳回本對象的引用

 return *this;

二:改錯題,隻能在原來的基礎上增加代碼,不能删除代碼

#include

void foo(int age,char *b)

   b = (char *)malloc(64);

   sprintf(b,"Your Age is %d",age);

int main()

  char *f;

  foo(23,f);

  printf("%s\n",f);

答案

void foo(int age,char **b)

   *b = (char *)malloc(64);

   sprintf(*b,"Your Age is %d",age);

  char **f;

  printf("%s\n",**f);

  return 0;

版本2

void foo(int age,char *&b)

  free(f);//不要忘了free;

繼續閱讀