• String实现


    #include <iostream>
    using namespace std;
    class String
    {
    public:
    	String(const char *str = NULL); // 通用构造函数
    	String(const String &another); // 拷贝构造函数
    	~ String(); // 析构函数
    	String& operator =(const String&);// 赋值函数
    	friend ostream& operator << (ostream&, const String& s);
    	friend istream& operator>>(istream& in, String& s);
    	friend String operator+(const String&,const String&);
    	bool operator==(const String &);
    private:
    	char *m_data; // 用于保存字符串
    };
    String::String(const char *str)
    {
       if (str == NULL)
          m_data = NULL;
       else
       {
    	   m_data = new char[strlen(str)+1];
           strcpy(m_data,str);
       }
    
    }
    String::String(const String &another)
    {
       m_data = new char[strlen(another.m_data)+1];
       strcpy(m_data,another.m_data);
    }
    String::~String()
    {
    	if(m_data != NULL)
    	{
    		delete []m_data;
    		m_data = NULL;
    	}
    }
    bool String::operator==(const String &s)
    {
    	if (strcmp(this->m_data,s.m_data))
    	    return true;
    	return false;
    }
    String & String::operator=(const String &rhs)
    {
      if (*this == rhs)
          return *this;
      delete []m_data;
      m_data = NULL;
      m_data = new char[strlen(rhs.m_data)+1];
      strcpy(m_data,rhs.m_data); 
      return *this;
    }
    ostream& operator << (ostream& out, const String& s)
    {
      if(s.m_data)
       out << s.m_data << endl;
      return out;
    }
    istream& operator>>(istream& in, String& s)
    {
    	char q[1000];
    	in >> q;
       s.m_data = new char[strlen(q)+1];
       strcpy(s.m_data,q); 
       return in;
    }
    String operator+(const String& lhs,const String&rhs)
    {
    	String *ret = new String(lhs);
    	strcat(ret->m_data,rhs.m_data);
    	return *ret;
    }
    int main()
    {
       String s ;
       cin >> s;
       String s1;
       cin >> s1;
       String s2 = s+s1;//this sentence has question , but i don't know why
       cout << s2;
    }
    
  • 相关阅读:
    python基础 2
    python基础 1
    进程
    进程作业
    上海python14期第二次阶段性考试
    面向对向之元类
    面向对向
    笔试题
    模块(2)
    模块作业
  • 原文地址:https://www.cnblogs.com/xiangshancuizhu/p/2119586.html
Copyright © 2020-2023  润新知