当前位置: 移动技术网 > IT编程>开发语言>C/C++ > c++运算符重载,MyString类

c++运算符重载,MyString类

2018年03月27日  | 移动技术网IT编程  | 我要评论

jojo的奇妙冒险第四部,日历女郎,禁毒主题班会教案

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;
}

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网