设为首页 加入收藏

TOP

string类的正确简明写法
2013-10-17 09:05:51 来源: 作者: 【 】 浏览:168
Tags:string 正确 简明 写法

  先说说程序员(应届生)面试的一般过程,一轮面试(面对一到两个面试官)一般是四、五十分钟,面试官会问两三个编程问题(通常是两大一小),因此留给每个编程题的时间只有 20 分钟。这 20 分钟不光是写代码,还要跟面试官讨论你的答案并解答提问,比如面试官拿过你的答案纸,问某一行代码如果修改会有什么后果。因此真正留给在纸上或白板上写代码的时间也就 10 分钟上下。本文给出了一个能用 10 分钟时间在纸上写出来且不会有错的 String class,强调正确性及易实现(白板上写也不会错),不强调效率与功能完备。

  #include #include // A trivial String class that designed for write-on-paper in an interviewclass String{ public: String()

  : data_(new char ) {

  *data_ = '\0'; } String(const char* str)

  : data_(new char[strlen(str) + 1]) {

  strcpy(data_, str); } String(const String& rhs)

  : data_(new char[rhs.size() + 1]) {

  strcpy(data_, rhs.c_str()); } /* Implement copy-ctor with delegating constructor in C++11 String(const String& rhs)

  : String(rhs.data_) { } */ ~String() noexcept {

  delete[] data_; } /* Traditional: String& operator=(const String& rhs) {

  String tmp(rhs);

  swap(tmp);

  return *this; } */ // In C++11, this is unifying assignment operator String& operator=(String rhs) // yes, pass-by-value {

  // http://en.wikibooks.org/wiki/More_C++_Idioms/Copy-and-swap

  swap(rhs);

  return *this; } // C++11 move-ctor String(String&& rhs) noexcept

  : data_(rhs.data_) {

  rhs.data_ = nullptr; } /* Not needed if we have pass-by-value operator=() above,

  * and it conflits. http://stackoverflow.com/questions/17961719/ String& operator=(String&& rhs) {

  swap(rhs);

  return *this; } */ // Accessors size_t size() const {

  return strlen(data_); } const char* c_str() const {

  return data_; } void swap(String& rhs) {

  std::swap(data_, rhs.data_); } private: char* data_;};

  =() above, * and it conflits. http://stackoverflow.com/questions/17961719/ String& operator=(String&& rhs) { swap(rhs); return *this; } */ // Accessors size_t size() const { return strlen(data_);

  }

  const char* c_str() const { return data_;

  }

  void swap(String& rhs) { std::swap(data_, rhs.data_);

  }

  private: char* data_;};

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇在程序中用C++支持多国语言 下一篇C语言实现有限自动机FSM

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: