C 運算子過載(複數類為例)

2021-10-04 11:48:48 字數 1202 閱讀 9930

/* 運算子過載(複數為例),兩種過載形式:過載為類的非靜態函式(加法),過載為非成員函式(減法)

* 實現 +,-,++,--,<< 運算子的過載

* date: mar,27

**/#include

#include

using

namespace std;

class

complex

// 複數類

complex operator+(

const complex c)

// 過載 +

complex operator++(

)// 過載前置++,沒有形參

complex operator++(

int)

// 過載後置++,有 int 形參

friend complex operator-(

const complex c1,

const complex c2)

;// - 過載為非成員函式

friend complex operator

--(complex &c)

;// 過載前置--

friend complex operator

--(complex &c,

int)

;// 過載後置--

friend ostream &

operator

<<

(ostream &out,

const complex c)

;// 過載 <<,只能過載為非成員函式

void

print()

private

:double real;

double imag;};

complex operator-(

const complex c1,

const complex c2)

complex operator

--(complex &c)

complex operator

--(complex &c,

int)

//ostream &

operator

<<

(ostream &out,

const complex c)

intmain

(void

)

C 複數類運算子過載

實現運算子過載有兩種形式 過載為成員函式 過載為友元函式。includeusing namespace std class complex complex double r,double i complex const complex rhs complex operator const compl...

C 運算子過載,複數類

複數類 ccomplex c 的運算子過載 使物件的運算表現的和編譯器內建型別一樣。include using namespace std class ccomplex ccomplex operator const ccomplex src void show 運算子的過載 operator 前置...

運算子過載 複數類

1.普通運算子可以過載 2.型別過載1 防止實參被修改 2 接收隱式生成臨時物件 類內是this call的呼叫約定,成員方法隱藏this指標,指向一般為左運算元,所以只用傳右運算元即可 如下 class ccomplex 構造類內實現 的過載 右運算元型別為intconst ccomplex op...