C++操作符重載

爲什麼需要對操作符進行重載?對於編譯器提供的操作符,一般情況下,只支持基本數據類型和標準庫中提供的class,對於用戶自己定義的class,如果想支持基本操作,比如比較大小,判斷是否相等,等等,則需要用戶自己來定義關於這個操作符的具體實現。比如,判斷兩個人是否一樣大,我們默認的規則是按照其年齡來比較,所以,在設計person 這個class的時候,我們需要考慮操作符==,而且,根據剛纔的分析,比較的依據應該是age。那麼爲什麼叫重載呢?這是因爲,在編譯器實現的時候,已經爲我們提供了這個操作符的基本數據類型實現版本,但是現在他的操作數變成了用戶定義的數據類型class,所以,需要用戶自己來提供該參數版本的實現。
操作符重載有兩種方式,一種是藉助類成員函數實現。另一種是藉助全局函數實現。
操作符重載的本質是函數,定義格式如下:

返回值 operator 操作符 (左操作數, 右操作數)

其中需要注意的是,對於返回值和左右操作數能用引用時儘量用引用。如果需要被重載的操作符支持鏈式編程,如<<、=,那麼返回值需要是一個引用。
下面通過定義一個數組類,來重載[]、=、==、!= 操作符。
頭文件.h

#ifndef _ARRAY_H_
#define _ARRAY_H_
class Array
{
public:
    Array(int length);
    Array(Array &obj);
    int GetData(int index);
    int Length();
    void SetData(int index, int value);
    ~Array();
private:
    int *space;
    int mlength;
public:
    int& operator[](int i);
    Array& operator=(Array &a1);
    bool operator==(Array &a1);
    bool operator!=(Array &a1);
};
#endif

.cpp文件

#include <iostream>
#include "Array.h"
Array::Array(int length)
{
    if (length < 0)
    {
        mlength = 0;
    }
    mlength = length;
    space = new int[mlength];
}
Array::Array(Array &obj)
{
    int i = 0;
    mlength = obj.mlength;
    space = new int[mlength];
    for (i = 0; i < mlength; i++)
    {
        space[i] = obj.space[i];
    }
}
int Array::GetData(int index)
{
    return this->space[index];
}
int Array::Length()
{
    return this->mlength;
}
void Array::SetData(int index, int value)
{
    if (index < 0 && index > mlength)
    {
        return;
    }
    this->space[index] = value;
}
Array::~Array()
{
    if (space != NULL)
    {
        delete[]space;
        mlength = -1;
    }
}

//重載=操作符
Array& Array::operator=(Array &obj)
{
    int i = 0;
    this->mlength = obj.mlength;
    this->space = new int[mlength];
    for (i = 0; i < this->mlength; i++)
    {
        this->space[i] = obj.space[i];
    }
    return *this;
}

//重載[]操作符
int& Array::operator[](int i)
{
    return this->space[i];
}

//重載==操作符
bool Array::operator==(Array &a1)
{
    int i = 0;
    if (this->mlength != a1.mlength)
    {
        return false;
    }
    for (i = 0; i < this->mlength; i++)
    {
        if (this->space[i] != a1.space[i])
        {
            return false;
        }
    }
    return true;
}
//重載!=操作符
bool Array::operator!=(Array &obj)//注重代碼的複用性
{
    return !(*this == obj);//直接複用前面的==代碼
}
發佈了36 篇原創文章 · 獲贊 16 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章