C 快速入門13 運算子過載

2021-10-05 09:59:51 字數 3331 閱讀 1620

在平時專案中,有時候需要自定義一些常規的運算子給某個功能用,那麼就必須重新定義這個符號的功能了。

有些運算子可以作為成員函式,有些運算子只能作為外部函式;

比如輸入輸出流函式只可作為外部函式;加法運算子既可以作為成員函式,也可以作為外部函式。

示例1-問題引入:

int

main()

cout << stu:這個語句想通過輸出流運算子直接將結構體資訊輸出,如按正常的功能,是不可以的;

示例1-解決(struct):

ostream&

operator

<<

(ostream &o, student s)

intmain()

**示例1-解決(class):**那麼我們可以在class內定義乙個友元函式:

class

student

//友元函式

friend ostream&

operator

<<

(ostream &o, student s);}

;ostream&

operator

<<

(ostream &o, student s)

intmain()

示例2-輸入流符號過載(class):

class

student

//友元函式

friend ostream&

operator

>>

(ostream &in, student &s);}

;ostream&

operator

>>

(ostream &in, student &s)

intmain()

示例3-下標運算子過載:

#include

#include

class

point

//自定義建構函式

point

(double x_,

double y_)

friend ostream&

operator

>>

(ostream &in, student &s)

;friend ostream&

operator

<<

(ostream &o, student s);}

;ostream&

operator

>>

(ostream &in, student &s)

intmain()

若想直接通過下標運算子賦值(即給私有成員賦值),那麼:

#include

#include

class

point

double

&operator

(int i)

//自定義建構函式

point

(double x_,

double y_)

friend ostream&

operator

>>

(ostream &in, student &s)

;friend ostream&

operator

<<

(ostream &o, student s);}

;ostream&

operator

>>

(ostream &in, student &s)

ostream&

operator

<<

(ostream &o, student s)

intmain()

示例3-加法運算子過載:外部函式實現:

int

main()

#include

#include

class

point

double

&operator

(int i)

//自定義建構函式

point

(double x_,

double y_)

friend ostream&

operator

>>

(ostream &in, student &s)

;friend ostream&

operator

<<

(ostream &o, student s);}

;point operator+(

const point p,

const point q)

ostream&

operator

>>

(ostream &in, student &s)

ostream&

operator

<<

(ostream &o, student s)

intmain()

內部函式實現:

class

point

double

&operator

(int i)

//自定義建構函式

point

(double x_,

double y_)

//新增這乙個內部函式,僅需乙個引數即可,第二個引數其實是本類內的私有成員

point operator+(

const point q)

friend ostream&

operator

>>

(ostream &in, student &s)

;friend ostream&

operator

<<

(ostream &o, student s);}

;

point s = p+q;這句就相當於p.operator+(q),operator+(p,q)

戳我,讓你走向成功的世界

13 運算子過載

所謂過載,就是重新賦予新的含義。函式過載就是對乙個已有函式賦予新的定義,使之實現新的功能,因此,乙個函式名就可以用來代表不同功能的函式,也就是 一名多用 運算子也可以過載,運算子過載的本質是乙個函式。class complex public void printcom double f operat...

C 入門 運算子過載

c 為了增強 的可讀性引入了運算子過載,對已有的運算子重新進行定義,賦予其另一種功能,運算子過載是具有特殊函式名的函式,也具有其返回值型別,函式名字以及引數列表,其返回值型別與引數列表與普通的函式類似。函式名字 operator後面接需要過載的運算子符號。函式原型 type operator操作符 ...

13 運算子過載(一)

運算子過載 對已有的運算子重新進行定義,賦予其另一種功能,以適應不同的資料型別 person personaddperson person p person operator person p include using namespace std class person int m a int ...