1.所謂重載,就是賦予其新的意義。函數(shù)可以重載,操作符也可以重載。操作符的重載給我們的編程帶來了很大的便利,因?yàn)椴僮鞣荒軐镜臄?shù)據(jù)類型進(jìn)行操作,而對用戶自定義的類等數(shù)據(jù)結(jié)構(gòu)類型不支持。因此只能對其操作符進(jìn)行重載之后,才能更加方便地操作我們自定義的類對象等數(shù)據(jù)類型。但是值得注意的是并不是C++中的所有運(yùn)算符都可以進(jìn)行操作。下面這些操作符就不可以:
. 成員訪問運(yùn)算符?: 條件運(yùn)算符(三目運(yùn)算符)* 成員指針訪問限定符sizeof 求對象長度操作符2.重載要注意的一些特征: (1) C++不允許用戶重新定義新的運(yùn)算符,只能對已經(jīng)存在的操作符號進(jìn)行重載; (2) 重載不能改變操作符的優(yōu)先級別; (3) 重載不能改變運(yùn)算符的運(yùn)算對象(即就是操作數(shù))的個(gè)數(shù),即三目運(yùn)算符仍然需要三個(gè)運(yùn)算對象,雙目運(yùn)算符需要兩個(gè)運(yùn)算對象等。 (4) 重載不能改變運(yùn)算符的結(jié)合性等。
3.運(yùn)算符的重載實(shí)質(zhì)上是函數(shù)的重載,是通過定義函數(shù)來實(shí)現(xiàn)的。運(yùn)算符重載函數(shù)不僅可以作為類的成員函數(shù),還可以作為全局函數(shù)。但是這里有兩個(gè)特殊的操作符是不能作為成員函數(shù)的,那就是<<(流插入運(yùn)算符)和>>(流提取運(yùn)算符)。重載運(yùn)算符的函數(shù)的一般格式如下:
函數(shù)類型 Operator 運(yùn)算符名稱(形參表) { 對運(yùn)算符的重載處理 }重載操作符 + - >> <<
#include <iostream>using namespace std;class Complex { //重載操作符>> friend istream &operator>>(istream &in, Complex &c); //重載操作符<< friend ostream &operator<<(ostream &out,Complex &c); //重載操作符- 通過全局函數(shù)的形式 friend Complex operator-(const Complex &c1,const Complex &c2); public: Complex(); //帶參數(shù)的構(gòu)造函數(shù) Complex(int real,int imag); //重載操作符+ Complex operator+(const Complex &c); PRivate: int m_real; int m_imag; };Complex::Complex() { this->m_imag=0; this->m_real=0; }Complex::Complex(int real,int imag) { this->m_real=real; this->m_imag=imag; }Complex Complex::operator+(const Complex &c) { Complex b; b.m_real=this->m_real+c.m_real; b.m_imag=this->m_imag+c.m_imag; return b; }Complex operator-(const Complex &c1,const Complex &c2) { Complex c; c.m_real=c1.m_real+c2.m_real; c.m_imag=c1.m_imag+c1.m_imag; return c; } ostream &operator<<(ostream &out,Complex &c) //cout<<t1<<t2; { out<<"("<<c.m_real<<","<<c.m_imag<<"i)"<<endl; return out; } istream &operator>>(istream &in,Complex &c2) { in>>c2.m_real>>c2.m_imag; return in; }int main(void) { Complex c1; Complex c2; Complex c3; cin>>c1>>c2; c3=c1-c2; cout<<c3; system ("pause"); return 0; }重載操作符:++(自增運(yùn)算符) 和 –(自減運(yùn)算符);這里又有前置++和后置++與前置–和后置–;操作符前置和后置的不同點(diǎn)是:操作符的后置中的括號里多了一個(gè)Int數(shù)據(jù)類型,當(dāng)然這個(gè)int數(shù)據(jù)類型沒有其他的作用,僅僅是用來區(qū)別操作符是前置運(yùn)算還是后置運(yùn)算,如:
數(shù)據(jù)類型 operator ++() //++i 前置++ 數(shù)據(jù)類型 operator ++(int) //i++ 后置++未完待續(xù)···············
新聞熱點(diǎn)
疑難解答
圖片精選