操作符過載(一)

2022-07-19 06:36:14 字數 3088 閱讀 7170

目錄2. 複數類的實現

3. 賦值操作符過載和拷貝建構函式

操作符過載的本質是用特殊形式的函式擴充套件操作符的功能

在進行操作符過載時,必須遵循以下三條規則

全域性函式和成員函式都可以實現對操作符的過載,過載為全域性函式的語法規則為

/*

* sign為預定義的操作符,如:+, -, *, /;

* lp和rp分別為左運算元和右運算元.

*/type operator sign (const type &lp, const type &rp)

如果過載為全域性函式,則需要在友元的輔助下才能實現,因此,一般選擇將操作符過載為類的成員函式

下面,我們通過乙個複數類,來分別實現算術運算操作符、比較操作符和賦值操作符的過載,以下是標頭檔案和原始檔的非過載部分**。

complex.h

#ifndef _complex_h_

#define _complex_h_

class complex

;#endif

complex.cpp

#include "complex.h"

#include complex::complex(double a, double b)

double complex::geta()

double complex::getb()

double complex::getmodulus()

complex.cpp

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

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

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

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

complex.cpp

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

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

complex.cpp

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

return *this;

}

注意,賦值操作符有幾點特殊之處:

賦值操作符過載和拷貝建構函式具有相同的作用和意義,那麼,c++什麼時候呼叫賦值操作符過載函式?什麼時候呼叫拷貝建構函式?

classname c1;

classname c2 = c1; //呼叫拷貝建構函式

classname c3(c1); //呼叫拷貝建構函式

classname c4;

c4 = c1; //呼叫賦值操作符過載函式

和拷貝建構函式類似

作為一般性原則,過載賦值操作符,必然需要實現深拷貝!!!

#include #include using namespace std;

class test

test(int i)

/*拷貝建構函式實現深拷貝*/

test(const test &obj)

/*過載賦值操作符實現深拷貝*/

操作符過載 一

一,運算子過載的基礎知識 1.什麼是運算子過載 所謂的過載,就是重新賦予新的含義。函式的過載是讓乙個已經存在的函式賦予乙個新的含義,使之實現新的功能。因此,乙個函式名就可以用來代表不同功能的函式。運算子的過載其實我們已經使用過了,例如常見的 加法操作就是c 預設過載的,我們可以用加法對整數,單精度,...

操作符過載

ifndef vertex h define vertex h class vertex vertex float px float py float pz vertex operator const vertex p vertex operator const vertex p void oper...

操作符過載

1.操作符是靜態方法,返回值表示操作結果,引數是運算元。2.操作符過載需要在過載的操作符前加上operator關鍵字。3.最好少用操作符過載,只有在意義明晰而且與內建類的操作一致時才適合使用,以免造成混亂。以建立的分數類 fraction 中的 為例,該分數類中有兩個int型的私有屬性 分子 num...