经典c++求职笔试题目

  想面试c++方面的职位,那么下面的求职笔试题目可能对您有帮助哦。

  1. 已知strcpy的函数原型:char *strcpy(char *strDest, const char *strSrc)其中strDest 是目的字符串,strSrc 是源字符串。不调用C++/C 的字符串库函数,请编写函数 strcpy。

  答案:

  复制代码

  #include <assert.h>

  #include <stdio.h>

  char*strcpy(char*strDest, constchar*strSrc)

  {

  assert((strDest!=NULL) && (strSrc !=NULL)); // 2分

  char* address = strDest;   // 2分

  while( (*strDest++=*strSrc++) !='\0' )       // 2分

  NULL;

  return address ;    // 2分

  }

  复制代码

  另外strlen函数如下:

  复制代码

  #include<stdio.h>

  #include<assert.h>

  int strlen( constchar*str ) // 输入参数const

  {

  assert( str != NULL ); // 断言字符串地址非0

  int len = 0;

  while( (*str++) !='\0' )

  {

  len++;

  }

  return len;

  }

  复制代码

  2. 已知String类定义如下:

  复制代码

  class String

  {

  public:

  String(const char *str = NULL); // 通用构造函数

  String(const String &another); // 拷贝构造函数

  ~String(); // 析构函数

  String& operater =(const String &rhs); // 赋值函数

  private:

  char* m_data; // 用于保存字符串

  };

  复制代码

  尝试写出类的成员函数实现。

  答案:

  复制代码

  String::String(constchar*str)

  {

  if ( str == NULL ) // strlen在参数为NULL时会抛异常才会有这步判断

  {

  m_data =newchar[1] ;

  m_data[0] ='\0' ;

  }

  else

  {

  m_data =newchar[strlen(str) +1];

  strcpy(m_data,str);

  }

  }

  String::String(const String &another)

  {

  m_data =newchar[strlen(another.m_data) +1];

  strcpy(m_data,other.m_data);

  }

  String& String::operator=(const String &rhs)

  {

  if ( this==&rhs)

  return*this ;

  delete []m_data; //删除原来的数据,新开一块内存

  m_data =newchar[strlen(rhs.m_data) +1];

  strcpy(m_data,rhs.m_data);

  return*this ;

  }

  String::~String()

  {

  delete []m_data ;

  }

  复制代码

本文已影响6827
上一篇:2016年最新c++面试笔试题 下一篇:2016年教师招聘考试笔试题目

相关文章推荐

|||||