C++之=运算符重载

1、类中没有指针成员

如果类中没有指针成员 ,不需要重载=运算,默认的浅拷贝就可以完成幅值。

#include <iostream>

using namespace std;
class Person
{
private:
    int a;
    int b;
public:
    Person():a(0),b(0)
    {
        cout<<"无参构造"<<endl;
    }
    Person(int a, int b):a(a),b(b)
    {
        cout<<"有参构造"<<endl;
    }
    void showPerson(void)
    {
        cout<<"a = "<<a<<", b = "<<b<<endl;
    }
    ~Person()
    {
        cout<<"析构函数"<<endl;
    }
};
void test01()
{
    Person ob1(10,20);
    ob1.showPerson();

    //注意 旧对象 给新对象赋值 调用的是拷贝构造(默认拷贝构造就是单纯的赋值)
    Person ob2 = ob1;//这个地方 可不是调用赋值=运算符
    ob2.showPerson();

    Person ob3;
    ob3 = ob1;//此处才是调用的赋值=运算符(默认赋值=运算是浅拷贝) 
    ob3.showPerson();
}
int main(int argc, char *argv[])
{
    test01();
    return 0;
}

2、类中 有指针成员 必须重载=运算符

指针作为类的成员:
1、拷贝构造函数 必须自定义(默认拷贝构造 是浅拷贝)
2、必须重载=运算符 (默认=号运算符 是浅拷贝)

注意
成员函数重载=运算符,要先释放this以前指向的空间

if(this->name != NULL)//说明this->name 以前有指向(重点)
        {
            //释放以前指向的空间
            delete [] this->name;
            this->name = NULL;
        }

最后返回 *this代表当前对象。
返回类型为引用,目的是可以迭代操作。

#include <iostream>
#include <cstring>
using namespace std;
class Person
{
private:
    char *name;//指针成员
public:
    Person()
    {
        name = NULL;
        cout<<"无参构造"<<endl;
    }
    Person(char *name)
    {
        //根据实际传入的 参数 给this->name申请空间
        this->name = new char[strlen(name)+1];

        //将name指向的字符串 拷贝到  this->name指向的空间中
        strcpy(this->name,name);

        cout<<"有参构造"<<endl;
    }
    Person(const Person &ob)//ob代表的就是旧对象
    {
        //this代表的是新对象
        cout<<"拷贝构造函数"<<endl;
        this->name = new char[strlen(ob.name)+1];
        strcpy(this->name, ob.name);
    }


    ~Person()
    {
        cout<<"析构函数"<<endl;
        if(this->name != NULL)
        {
            delete [] this->name;
            this->name = NULL;
        }
    }

    void showPerson(void)
    {
        cout<<"name = "<<name<<endl;
    }
    //成员函数 重载=运算符
    Person& operator=(Person &ob)//ob == ob1
    {
        //this ==>&ob3
        if(this->name != NULL)//说明this->name 以前有指向(重点)
        {
            //释放以前指向的空间
            delete [] this->name;
            this->name = NULL;
        }

        //申请空间
        this->name = new char[strlen(ob.name)+1];
        //拷贝内容
        strcpy(this->name,ob.name);

        return *this;//重点
    }
};

void test01()
{
    Person ob1("lucy");
    ob1.showPerson();

    Person ob2 = ob1;//调用拷贝构造

    Person ob3("bob");
    //不重载 = 默认是浅拷贝
    ob3 = ob1;

    ob3.showPerson();

    Person ob6,ob5,ob4;
    ob6 = ob5 = ob4 = ob1;
    ob6.showPerson();
}
int main(int argc, char *argv[])
{
    test01();
    return 0;
}

发布了24 篇原创文章 · 获赞 13 · 访问量 3119

猜你喜欢

转载自blog.csdn.net/Evan_work/article/details/105061032
今日推荐