zoukankan      html  css  js  c++  java
  • String 类的实现

    #include "stdafx.h"
    #include <iostream>
    using namespace std;
    
    class MyString
    {
    public:
     MyString(const char *str = NULL);   //通用拷贝构造函数
     MyString(const MyString &another);  //拷贝构造函数
     ~MyString();  //析构函数
     MyString& operator = (const MyString&); //赋值函数
    
     friend ostream& operator << (ostream&, const MyString& s);
     friend istream& operator >> (istream& in, MyString& s);
     friend MyString operator + (const MyString&, const MyString&);
     bool operator == (const MyString&);
    private:
     char* m_data;  //用于保存字符串
    };
    
    MyString::MyString(const char *str )
    {
     if ( NULL==str )
      m_data = NULL;
     else
     {
      m_data = new char[strlen(str)+1];
      strcpy(m_data,str);
     }
    }
    
    MyString::MyString(const MyString &another)
    {
     m_data = new char[strlen(another.m_data)+1];
     strcpy(m_data,another.m_data);
    }
    
    MyString::~MyString()
    {
     if( m_data != NULL )
     {
      delete []m_data;
      m_data = NULL;
     }
    }
    
    MyString& MyString::operator=(const MyString& 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 MyString& s) { if (s.m_data) out<<s.m_data<<endl; return out; } istream& operator >> (istream& in, MyString& s) { char q[1000]; in>>q; s.m_data = new char[strlen(q)+1]; strcpy(s.m_data, q); return in; } MyString operator+(const MyString& lhs, const MyString& rhs) { MyString *ret = new MyString(lhs); strcat(ret->m_data, rhs.m_data); return *ret; } int _tmain(int argc, _TCHAR* argv[]) { MyString s; cin >> s; MyString s1; cin >> s1; MyString s2 = s+s1; cout << s2; return 0; } 有可能你在使用 strcpy 的时候 会碰到这个错误:(VS2012碰到的) error C4996: 'strcpy': This function or variable may be unsafe. Consider using strcpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details. 1> d:microsoftvisiostudiovs2012_ult_enusetupvcincludestring.h(110) : see declaration of 'strcpy' 没关系:这个问题的解决方式是这样的 右键项目-》“Properties”-》“C/C++”-》“Preprocessor” 在Preprocessor Definitions 中添加 _CRT_SECURE_NO_WARNINGS 即可解决这个问题
  • 相关阅读:
    LINUX 修复relocation error: /lib/tls/libc.so.6
    cmd 命令相关
    JS 相关
    Mysql 时间函数
    drupal 7.1 doc
    消息系统之Apache ActiveMQ
    【MongoDB学习之一】初始MongoDB
    【Redis学习之二】Redis:redis.conf 配置详解
    【Redis学习之一】Redis
    NOSQL学习之一:Memcached, Redis, MongoDB区别
  • 原文地址:https://www.cnblogs.com/MrGreen/p/3294410.html
Copyright © 2011-2022 走看看