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 即可解决这个问题
  • 相关阅读:
    使用Spring Cloud Feign作为HTTP客户端调用远程HTTP服务
    聊聊高并发系统之限流特技
    Java程序员 必须掌握的 20+ 种 Spring 常用注解
    这20个核心技术,作为Java开发程序员,你一定要掌握
    40K刚面完Java岗,这些技术必须掌握
    Java 5,6,7,8,9,10,11新特性超详细总结
    小米程序员的忧虑:感觉互联网这两年要凉,想回家种地
    Java技术文档—Java中的运算符有哪些?
    Java笔记之数组,异常处理,集合知识要点
    Java学习笔记——IO流基础知识点整理
  • 原文地址:https://www.cnblogs.com/MrGreen/p/3294410.html
Copyright © 2011-2022 走看看