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 即可解决这个问题
  • 相关阅读:
    react的50个面试题
    什么是宏队列跟微队列
    宏队列与微队列
    数组都有哪些方法
    vuex 跟 vue属性
    高阶组件
    如何创建视图簇(View cluster)-SE54/SM34
    ◆◆0如何从维护视图(Maintenace view)中取数据-[VIEW_GET_DATA]
    ◆◆0如何在SM30维护表时自动写入表字段的默认值-事件(EVENT)
    ◆◆0SAP Query 操作教程
  • 原文地址:https://www.cnblogs.com/MrGreen/p/3294410.html
Copyright © 2011-2022 走看看