OOP 運算子過載

2021-10-24 17:17:27 字數 3066 閱讀 4766

運算子過載:

即寫函式去改變運算子的功能

以下的運算子都可以被過載

雙目算術運算子

關係運算子

邏輯運算子

單目運算子

自增自減運算子

位運算子

賦值運算子

空間申請與釋放

其他運算子

以下不能過載

.:成員訪問運算子

.*, ->*:成員指標訪問運算子

:::域運算子

sizeof:長度運算子

?::條件運算子

# 預處理符號

如下( 成員函式)

當運算子過載為類的成員函式時,函式的引數個數比原來的運算元要少乙個(後置單目運算子除外),這是因為成員函式用this指標隱式地訪問了類的乙個物件,它充當了運算子函式最左邊的運算元。

const string sting ::

operator+(

const string & that)

;

《物件名》.operator 《運算子》(《引數》)

它等價於

《物件名》《運算子》《引數》

乙個例子

#include

using

namespace std;

classa~

a() a operator+(

const a & b)

print()

private

:int ii;};

intmain()

#結果a::a(

)a::a(

)a::a(

)30a::~a(

)->

30a::~a

()->

20a::~a

()->

10

全域性函式(如下)

const string operator+(

const string & r,

const string &l)

;

operator 《運算子》(《引數1>,《引數2>)

它等價於

《引數1>《運算子》《引數2>

例如:a+b等價於operator +(a,b)。

如下

const integar operator-(

)const

z =-x;

= (x.operator-());

單目的以及下面的必須做成成員函式,其他的可以不做成成員函式

=()

->

->

*

運算子不能修改運算元的用const,但是如++,–不能加const

一些運算子的原型(返回的是乙個新物件)

//+ - */ % ^ & | ~

const t operator x (

const t&l,

const t&r)

const

;//! && || < <= == >= >

bool

operator x (

const t&l,

const t&r)

const;//

t & t::

operator

(int index)

;

int是為了區分++在左或者右,++a返回a,a++返回乙個新物件。

const integer & integer::

operator++(

)const integer integer::

operator++(

int)

bool integer::

operator==(

const integer& rhs)

bool integer::

operator!=(

const integer& rhs)

const

bool integer::

operator

<

(const integer& rhs)

const

bool integer::

operator

>

(const integer& rhs)

const

bool integer::

operator

<=

(const integer& rhs)

const

bool integer::

operator

>=

(const integer& rhs)

const

class

vector

~vector()

int&

operator

(int index)

private

:int m_size;

int*m_array;

};

乙個賦值的例子,為了使指標物件也不出錯,最好這樣寫

t& t::

operator=(

const t& rhs)

return

*this

;}

用來做型別轉換的運算子

編譯器會把one轉換為two,再呼叫f(自動型別轉換)

class

one}

;class

two}

;void

f(two)

intmain()

若想取消自動型別轉換,這樣寫建構函式

explicit

pathname

(const string &

);

轉換的另種方法

rational ::

operator

double()

const

OOP 運算子過載原型

include using namespace std 沒有temp變數的都可以加引用,有temp的,如果加引用必須加static 如果是可以連用 如 不改變其意思必須加引用 istream過載時,不能加const 型別轉換過載時,不能加返回值 輸入輸出過載必須為友元 class a a opera...

c 學習 oop 過載算數運算子

date 11 03 21 19 36 description 過載算數運算子 算術運算子 為了與內建操作符保持一致,算術操作符通常產生乙個新值 一般應使用復合賦值實現算術操作符 例如 用 來實現 include using namespace std class sales item sales ...

運算子過載之過載型別運算子

普通型別 類型別 呼叫對應的只有乙個引數 引數的型別就是這個普通型別 的建構函式 需求 boy boy1 10000 薪資 建構函式boy int boy boy2 rock 姓名 建構函式boy char 普通型別賦值給類型別其實很簡單,就是專門的對這個賦值的型別定義乙個建構函式。編譯器在執行 的...