37_重載=運算符

前提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、必須重載=運算符 (默認=號運算符 是淺拷貝)

#include <iostream>
#include<string.h>
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;
}

運行結果:

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章