C++運算子過載
阿新 • • 發佈:2018-12-11
一、運算子過載 C++中運算子過載允許將標準運算子運用在自己定義的類的物件,包括物件之間的運算等等。
二、運算子過載的型別 1、成員函式的過載 2、友緣函式的過載
三、運算子過載規則 1、不能有新的運算子 2、運算子過載後自身的優先順序以及結合規則不變 3、不能過載運算子有: 作用域解析運算子 :: 條件運算子 ?; 直接成員訪問運算子 . 運算子 sizeof
四、運算子過載特點 1、提高了程式碼的易讀性 2、也屬於一種函式呼叫方式 3、它的本質是函式的過載
五、實現基本的運算子過載
#include<iostream> using namespace std; //初始化 class CComplex { public: class CComplex() :_real(int()),_image(int()) {} CComplex(int real, int image) :_real(real), _image(image) {} //拷貝建構函式 CComplex(const CComplex &src) :_real(src._real), _image(src._image) {} //等號運算子的過載函式 CComplex &operator=(const CComplex& src) { if (this == &src) { return *this; } _real = src._real; _image = src._image; return *this; } //+運算子的過載 (this,CComplex&) CComplex operator+(/*this,*/const CComplex& src) { return CComplex(_real + src._real, _image + src._image); } //+運算子的過載 (this,int) CComplex operator+(int a) { return CComplex(_real + a, _image); } // -運算子的過載 (this,CComplex&) CComplex operator-(const CComplex& src) { return CComplex(_real - src._real, _image - src._image); } // -運算子的過載 (this,int) CComplex operator-(int a) { return CComplex(_real - a, _image); } //輸出運算子的過載 ostream& operator<<(/*this,*/ostream &out)//cout<<c3 { out << _real << " "; out << _image << " "; return out; } //輸入運算子的過載 istream& operator>>(istream& in) { in >> _real; in >> _image; return in; } //前置++ const CComplex &operator++(/*this*/) { ++_real; ++_image; return *this; } //後置++ const CComplex operator++(int) { //10 15 return CComplex(_real++, _image++);//CComplex(10,15) } //前置-- const CComplex &operator--() { --_real; --_image; return *this; } //後置-- const CComplex operator--(int) { return CComplex(_real--,_image--);//這裡返回的是一個臨時量 } //臨時量是一個常量,不可以修改 bool operator==(const CComplex& src) { return (_real == src._real && _image == src._image); } void show() { cout << _real << " " << _image << endl; } private: int _real; int _image; friend CComplex operator+(int a, const CComplex& src); friend CComplex operator-(int a, const CComplex& src); friend ostream& operator<<(ostream & out, const CComplex &src); friend istream& operator>>(istream& in, CComplex &src); }; //+ 運算子的過載 (int,CComplex) CComplex operator+(int a, const CComplex& src) { return CComplex(src._real + a, src._image); } //- 運算子的過載 (int,CComplex) CComplex operator-(int a, const CComplex& src) { return CComplex(a - src._real, src._image); } //輸出運算子過載 ostream& operator<<(ostream & out, const CComplex &src) { out << src._real << " "; out << src._image << " "; return out; } //輸入運算子過載 istream& operator>>(istream & in, CComplex &src) { in>>src._real; in>>src._image; return in; }