c语言入门:c++运算符重载

来源:互联网 发布:java 解析swf 编辑:程序博客网 时间:2024/06/08 00:27

MyString 类:

#ifndef MYSTRING_H#define MYSTRING_H#include <iostream>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 <string.h>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"<<endl;    }}ostream& operator<<(ostream& o,MyString& str){    o << str.m_str;    return o;}istream& operator>>(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<m_len;i++){            if(m_str[i]!=str[i]){                return false;            }        }    }    return true;}bool MyString::operator==(const char* str){    if(m_len!=strlen(str)+1){        return false;    }else{        for(int i=0;i<m_len;i++){            if(m_str[i]!=str[i]){                return false;            }        }    }    return true;}bool MyString::operator!=(MyString& str){    return !(*this==str);}bool MyString::operator!=(const char* str){    return !(*this==str);}int MyString::operator<( MyString& str){    return strcmp(m_str,str.m_str);}int MyString::operator<(const char* str){    return strcmp(m_str,str);}int MyString::operator>( MyString& str){    return strcmp(m_str,str.m_str);}int MyString::operator>(const char* str){    return strcmp(m_str,str);}

测试用例:

#include <iostream>#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;}
原创粉丝点击