设为首页 加入收藏

TOP

c++运算符重载,MyString类
2017-09-26 08:55:06 】 浏览:10121
Tags:运算 重载 MyString

MyString 类:

#ifndef MYSTRING_H
#define MYSTRING_H

#include 
  
   
using namespace std;

class MyString
{
public:
    friend ostream& operator<<(ostream& o,MyString& str);
    friend istream& operator>>(istream& o,MyString& str);

    MyString(char* str);
    MyString(const MyString& str);
    ~MyString();

    MyString& operator=(const MyString& str);
    char& operator[](int i);
    bool operator==( MyString& str);
    bool operator==(const char* str);
    bool operator!=( MyString& str);
    bool operator!=(const char* str);

    int operator<( MyString& str);
    int operator<(const char* str);
    int operator>( MyString& str);
    int operator>(const char* str);



private:
    char* m_str;
    int m_len;

};

#endif // MYSTRING_H

  
#include "mystring.h"
#include 
  
   


MyString::MyString(char* str)
{

    m_len=strlen(str)+1;
    m_str=(char*)malloc(m_len);
    strcpy(m_str,str);
}
MyString::MyString(const MyString& str)
{
    m_len=strlen(str.m_str)+1;
    m_str=(char*)malloc(m_len);
    strcpy(m_str,str.m_str);

}
MyString::~MyString()
{

    m_len=0;
    if(m_str!=NULL){
        free(m_str);
        m_str=NULL;
        cout<<"free"<
   
    >(istream& i,MyString& str){ i >> str.m_str; return i; } MyString& MyString::operator=(const MyString& str){ m_len=strlen(str.m_str)+1; m_str=(char*)malloc(m_len); strcpy(m_str,str.m_str); return *this; } char& MyString::operator[](int i){ return m_str[i]; } bool MyString::operator==( MyString& str){ if(m_len!=str.m_len){ return false; }else{ for(int i=0;i
    
     ( MyString& str){ return strcmp(m_str,str.m_str); } int MyString::operator>(const char* str){ return strcmp(m_str,str); } 
    
   
  

测试用例:

#include 
  
   
#include "mystring.h"
using namespace std;

int main()
{


    MyString str1("12333");
    MyString str2=str1;

    MyString str3("123111");
    //    str3=str1;

    //    str3[1]='2';

    //    cout << str3[1];

//    if(str3!=str1){
//        cout<<"不相等";

//    }else{
//        cout<<"相等";
//    }



    cout << "请输入str3:" << endl;
    cin >> str3;
    cout << str3 << endl;

    return 0;
}

  
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇C++11Auto关键字及注意点 下一篇c++函数传递指针的本质与字符串指..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目