zoukankan      html  css  js  c++  java
  • C++面试题String函数实现

    C++面试题-String函数实现

    面试中经常会出现让应聘者写出string的构造函数、析构函数等具体实现,有人说会了这道题,那么C++的基础知识可以说是会了60%.

    而且在前几天我同学参加的面试中也出现了这道题目,足以证明不负其名。为以后实习工作打算,现在将其总结一下。

     

    在网上搜了搜,发现很多文章列出了实现代码,但在重载“赋值函数”时都将operator错写成了operate,大家在参考代码的时候一定要注意。

    为方便测试,我还重载了输出符“<<”和输入符“>>”。

    最后给出了测试代码。

    #include <iostream>
    using namespace std;

    class String
    {
    public:
     String(const char *str = NULL); // 通用构造函数
     String(const String &another); // 拷贝构造函数
     ~ String(void); // 析构函数
    friend String & operator = (const String &rhs); // 赋值函数
    friend ostream& operator << (ostream& output, String & str); //重载输出符 “<<”
    friend istream& operator >> (istream& input, String& str);//重载输入符 >>

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

    istream& operator >> (istream& input, String& str)
    {
     input >> str.m_data;
     return input;
    }

    ostream& operator << (ostream &output, String &str)
    {
     output << str.m_data;
     return output;
    }
    String::~ String()

     cout << "Destructing !" << endl;
     delete m_data;
    }

    String::String(const char *str)
    {
     if(str == NULL)
     {
      this->m_data = new char[1];
      this->m_data = '\0';
     }
     else
     {
       this->m_data = new char[strlen(str) + 1];
       strcpy(m_data, str); 
     }
    }

    String::String(const String& another)
    {
     this->m_data = new char[strlen(another.m_data) + 1];
     strcpy(this->m_data, another.m_data);
    }

    String& String::operator = (const String &other)
    {
     if(this == &other)
      return *this;
     delete m_data;
     m_data = new char[strlen(other.m_data) + 1];
     strcpy(m_data, other.m_data);
    }

    int main()
    {
     String a("hello");
     String b("world!");
     cout << a << " " << b << endl;
     cin >> a >> b;
     cout << a << " " << b << endl;
     return 0;
    }

  • 相关阅读:
    tar打包split分割分解拆分大包文件
    SAP 语言码转换
    SAP audit S41909
    电商收付通系列<1>图片上传API
    Ladon7.4 CVE-2020-0688 Exchange序列化漏洞利用
    [反诈骗]入侵骗子电脑-揭秘冒充企业老板诈骗全过程
    Ladon插件-CVE-2020-1472域控提权漏洞EXP
    Winrm远程命令/端口复用后门/WinrmCmd/密码爆破
    〖教程〗Ladon WinrmExec远程执行命令
    Ladon插件-批量检测网站是否使用Shiro
  • 原文地址:https://www.cnblogs.com/smileallen/p/3391523.html
Copyright © 2011-2022 走看看