15 C 操作符過載 並實現複數類

2021-09-07 17:27:31 字數 4147 閱讀 2351

首先回憶下以前學的函式過載

函式過載

類中的函式過載

操作符過載(operator)

什麼是操作符過載?

大家都知道,在c裡,有'+,-,*,/'這些操作符,且它們的功能就是實現普通變數運算。

由於c++是物件導向的,遇到的變數大多都是物件,所以優化了c裡的操作符,使它們擁有了過載能力.能通過一定方式,使物件能進行'+,-,*,/'等運算.

操作符的過載是以函式的方式進行.

操作符過載定義

操作符過載,通過operator關鍵字在函式前定義:

[返回型別]  operator  [需要過載的操作符](函式引數)

操作符過載有幾種方式 : 全域性操作符過載函式、全域性操作符過載函式編譯器首先會判斷運算的若是物件,就會先從類裡尋找成員操作符過載函式,若沒找到,就會再去全域性裡尋找全域性操作符過載函式.注意事項:比如賦值(=)、下標()、下標()、呼叫(())和成員訪問箭頭(->):

test t3=t2;   //相當於呼叫了: test  t3.operator =(t2);  裡面會通過this指標來代替左側數t3
比如加法(+),與(&&),或(||),逗號(,)等:

以加法(+)為例,當設為全域性操作符過載函式時,執行

test t3=t1+t2;  //相當於呼叫了:  test t3 = operator +(t1,t2);
以加法(+)為例,當設為成員操作符過載函式時,執行

test t3=t1+t2;  //相當於呼叫了:  test t3 =t1.operator +(t2);  //裡面會通過this指標來代替左側數t1
多個過載的操作符過載函式由於操作符過載函式帶引數,所以可以存在多個相同的操作符過載函式

例如:

class test

;

初步試驗1.接下來,來個全域性操作符過載函式例子:

#include "stdio.h"

class test

int getx()

int gety()

friend test operator + (const test& t1,const test& t2);

//宣告友元函式,可以使用私有成員變數

};test operator + (const test& t1,const test& t2) //過載

int main()

列印結果:

t3.x:3  t3.y:7

t4.x:4 t4.y:10

2.換成成員操作符過載函式例子:

#include "stdio.h"

class test

int getx()

int gety()

test operator + (const test& t2)

};int main()

列印結果:

t3.x:3  t3.y:7

t4.x:4 t4.y:10

加深理解由於c++裡,沒有複數的慨念,而在剛剛又學習了操作符過載,所以接下來便通過操作符過載來實現複數類複數類應該具有兩個成員

實部a 、虛部b

運算操作符

+ -:  結果 = 兩個實部進行加減,兩個虛部進行加減

*:  結果 = (a1+b1)(a2+b2)= (a1*a2 - b1*b2 )+( a2*b1 + a1*b2);

/:  結果 =(a1+b1)/(a2+b2)= (a1*a2+b1*b2)/(a2* a2+b2* b2) +(b1*a2-a1*b2)/(a2* a2+b2* b2)

比較操作符:== ,!=

賦值操作符:=

求模成員函式 :等於a^2+b^2的算術平方根

所以複數類的操作符過載共有以下幾個:

1.寫標頭檔案complex.h:

#ifndef __complex_h

#define __complex_h

class complex;

#endif

2.寫原始檔complex.cpp

#include "complex.h"

#include "math.h"

complex::complex(int a,int b)

complex complex::operator + (const complex& t)

complex complex::operator - (const complex& t)

complex complex::operator * (const complex& t)

complex complex::operator / (const complex& t)

bool complex::operator == (const complex& t)

bool complex::operator != (const complex& t)

complex& complex::operator = (const complex& t)

return *this;

}

double complex::getmodulus()

double complex::geta()

double complex::getb()

3.寫測試檔案test.cpp

#include "stdio.h"

#include "complex.h"

int main()

4.編譯執行

t3.a=3.000000  t3.b=9.000000

t3 modulus:9.486833

t4==t3: 1 //為真

t4!=t3: 0 //為假

t3==t1: 0 //為假

C 操作符過載 並實現複數類詳解

首先回憶下以前學的函式過載 函式過載 類中的函式過載 操作符過載 operator 什麼是操作符過載?大家都知道,在c裡,有 這些操作符,且它們的功能就是實現普通變數運算。由於c 是物件導向的,遇到的變數大多都是物件,所以優化了c裡的操作符,使它們擁有了過載能力.能通過一定方式,使物件能進行 等運算...

操作符過載(複數類 陣列類 函式物件)

目錄 操作符過載與複數類 陣列操作符的過載 函式呼叫操作符 c 中的過載能夠以特殊形式的函式的擴充套件操作符的功能 通過operator關鍵字可以定義特殊的函式 operator的本質是通過函式過載操作符 type operator sign const type p1,const type p2 ...

C 類操作符過載筆記

不能改變操作符優先順序 不能改變操作符的結合性 不能改變操作符所需要的運算元 不能建立新的操作符 對於二元操作符過載,如果操作符左邊是類 那麼就在該類內部成員函式過載操作符即可 如果操作符左邊不是類,而是乙個常量,那麼就必須在類的外部定義乙個操作符過載函式 有乙個最基本條件 一定有乙個一元是乙個自定...