• 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;
    }

  • 相关阅读:
    [CLK Framework] CLK.Settings
    [Architecture Design] CLK Architecture
    记一次 bug 修复 , 未将对象引用实例化
    Invoke 与 BeginInvoke 应用场景
    一次发布生产版程序异常排查总结
    C# 使用 SmtpClient 发送邮件注意项
    MSSql Server 批量插入数据优化
    Window Server 布署 WCF 服务 , 权限配置问题
    C++ 值类型和引用类型传递示例
    VS2015 C#调用C++ 托管代码无法调试问题排查
  • 原文地址:https://www.cnblogs.com/smileallen/p/3391523.html
Copyright © 2020-2023  润新知