zoukankan      html  css  js  c++  java
  • 赋值运算符重载

    一个类默认创建时 默认构造、析构、拷贝构造和operator=赋值运算符重载(浅拷贝) 进行简单的值传递

    1.1          系统默认给类提供 赋值运算符写法 是简单值拷贝

    1.2          导致如果类中有指向堆区的指针,就可能出现深浅拷贝的问题

    #define _CRT_SECURE_NO_WARNINGS
    #include <iostream>
    using namespace std;
    
    class Person
    {
    public:
        Person(int a)
        {
            this->m_A = a;
        }
    
        int m_A;
    };
    
    void test()
    {
        Person p1(10);
        Person p2(0);
        p2 = p1;        //通过默认的operator= 进行浅拷贝 把p1的成员属性复制给p2
        cout << "p2.m_A = " << p2.m_A << endl;
    }
    int main()
    {
        test();
        system("Pause");
        return 0;
    }

    结果:

    1.3          所以要重载 = 运算符

    #define _CRT_SECURE_NO_WARNINGS
    #include <iostream>
    using namespace std;
    
    class Person
    {
    public:
        Person(int a)
        {
            this->m_A = a;
        }
    
        int m_A;
    };
    
    
    void test()
    {
        Person p1(10);
        Person p2(0);
        p2 = p1;        //通过默认的operator= 进行浅拷贝 把p1的成员属性复制给p2
        cout << "p2.m_A = " << p2.m_A << endl;
    }
    
    class Person2
    {
    public:
        Person2(const char* name)
        {
            this->p_Name = new char[strlen(name) + 1];
            strcpy(this->p_Name, name);
        }
    
    
        ~Person2()
        {
            if (this->p_Name != NULL)       //释放资源
            {
                delete[] this->p_Name;
                this->p_Name = NULL;
            }
        }
    
        //为了防止浅拷贝导致资源被重复释放出错
        //重载 = 赋值运算符
        void operator=(const Person2& p)
        {
            //判断如果原来已经有了堆区的内容,先释放
            if (this->p_Name != NULL)
            {
                delete[] this->p_Name;
                this->p_Name = NULL;        
            }
            this->p_Name = new char[strlen(p.p_Name) + 1];
            strcpy(this->p_Name, p.p_Name);
        }
    
        char* p_Name;
    };
    
    void test02()
    {
        Person2 p1("小熊");
        Person2 p2("小能");
        p2 = p1;         //调用operator=函数   
        //由于p2已经创建,不需要再调用构造函数,这时候调用的是重载的赋值运算符
        cout << "p2的名字:" << p2.p_Name << endl;    //打印后会报错,因为operator=默认是浅拷贝,p1资源被释放掉了 p2再次释放的时候就会报错
                                                      //重载operator=后 没有问题
    }
    int main()
    {
        test02();
        //test();
        system("Pause");
        return 0;
    }

    1.4          如果想链式编程 return*this

    此时想要链式编程还是不行,

    因为重载的赋值运算符并无返回值 返回的是void 所以无法组成链式编程,需要返回对象本身,所以

    此时就可以进行链式编程了

    结果:

     

  • 相关阅读:
    python 字符编码
    python 模块 json
    python 命令空间
    python 装饰器
    ItemsControl Grouping分组
    WPF CanExecuteChanged
    WPF 控件树
    Bingding模型
    WCF中的AsyncPattern
    WPF中获取指定坐标依赖对象数据项
  • 原文地址:https://www.cnblogs.com/yifengs/p/15175527.html
Copyright © 2011-2022 走看看