天天看点

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;

继续阅读