• 操作符重载引入


    运算符重载前:
    #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;
    }
  • 相关阅读:
    Vue之数据排序加签
    微信小程序之评分页面
    Vue之展示PDF格式的文档
    动态规划问题思考(DP)
    LitJson的使用
    c#事件管理器
    unity shader 学习
    unity ugui图片自适应文字内容大小
    unity3d各种OpenFileDialog操作
    ue4 使用3dsmax制作布料的插件及下载位置
  • 原文地址:https://www.cnblogs.com/letben/p/5301916.html
Copyright © 2020-2023  润新知