操作符重载引入

运算符重载前:
#include <iostream>
#include <string.h>
#pragma warning(disable:4996)
using namespace std;
class MyString{
public :
    char *str;
    MyString(){
        cout << "无参构造地址:"<<&str << endl;
        str = new char[256];
    }
    MyString(const MyString &mystr){//复制构造
        str = new char[256];
        memset(str, 0, 256);
        strcpy(str, mystr.str);
    }

    ~MyString(){
        cout << "析构" <<&str<< endl;
        delete[]str;
    }
};
int main(){
    MyString ms1;
    strcpy(ms1.str, "letben");
    /*
    问题代码:
    MyString ms2;
    ms2 = ms1;
    cout << ms1.str << endl;
    cout << ms2.str << endl;
    */
    //调用了复制构造函数,所以没有出问题。所以=方式与复制构造函数上还是有本质差别的。
    MyString ms3(ms1);
    cout << ms1.str << endl;
    cout << ms3.str << endl;
    MyString ms4(ms1);
    cout << ms1.str << endl;
    cout << ms4.str << endl;
    //可是细细想来,ms2 = ms1  应该是一个靠谱的写法。所以我们要是可以把这种运算也做成是,复制构造的样子就好了。可是怎么才能让 这个= 不变成浅拷贝,而变成我们所希望它的样子呢?
    //这就引出了,运算符的重载。让“=”执行我们的功能。
    system("pause");
    return 0;
}

运算符重载之后的代码:

#include <iostream>
#include <string.h>
#pragma warning(disable:4996)
using namespace std;
class MyString{
public :
    char *str;
    MyString(){
        cout << "无参构造地址:"<<&str << endl;
        str = new char[256];
    }
    MyString(const MyString &mystr){//复制构造
        str = new char[256];
        memset(str, 0, 256);
        strcpy(str, mystr.str);
    }
    ~MyString(){
        cout << "析构" <<&str<< endl;
        delete[]str;
    }
    /* 重载“=”运算符*/
    void operator =(const MyString &mystr){
        str = new char[256];
        memset(str, 0, 256);
        strcpy(str, mystr.str);
    }
};
int main(){
    MyString ms1;
    strcpy(ms1.str, "letben");
    /*
    问题代码:
    MyString ms2;
    ms2 = ms1;
    cout << ms1.str << endl;
    cout << ms2.str << endl;
    */
    //调用了复制构造函数,所以没有出问题。所以=方式与复制构造函数上还是有本质差别的。
    MyString ms3(ms1);
    cout << ms1.str << endl;
    cout << ms3.str << endl;
    MyString ms4(ms1);
    cout << ms1.str << endl;
    cout << ms4.str << endl;
    //可是细细想来,ms2 = ms1  应该是一个靠谱的写法。所以我们要是可以把这种运算也做成是,复制构造的样子就好了。可是怎么才能让 这个= 不变成浅拷贝,而变成我们所希望它的样子呢?
    //这就引出了,运算符的重载。让“=”执行我们的功能。
    MyString ms2;
    ms2 = ms1;
    system("pause");
    return 0;
}

 

posted on 2016-03-21 14:48  木鸟飞  阅读(220)  评论(0编辑  收藏  举报

导航