小甲魚-C++快速入門筆記 25 之運算子過載1
阿新 • • 發佈:2021-01-13
所謂過載,就是重新賦予新的含義。函式過載就是對一個已有的函式賦予新的含義,使之實現新的功能。
而運算子過載的方法是定義一個過載運算子的函式,在需要執行被過載的運算子時,系統就自動呼叫該函式,以實現相應的運算。運算子過載時通過定義函式實現的,運算子過載實質上是函式的過載。
過載運算子的函式一般格式如下:
例如我們過載運算子+,如下:
int operator+(int a,int b)
{
return (a-b);
}
舉個例子:實現複數加法
(3,4i)+(5,-10i)=(8,-6i)
不用過載:
#include <iostream> using namespace std; class Complex { public: Complex(); Complex(double r, double i); //帶引數的建構函式 Complex complex_add(Complex &d); void print(); private: double real; double imag; }; Complex::Complex() { real = 0; imag = 0; } Complex::Complex(double r, double i) { real = r; imag = i; } Complex Complex::complex_add(Complex &d) { Complex c; c.real = real + d.real; c.imag = imag + d.imag; return c; } void Complex::print() { cout << "(" << real << "," << imag << "i)\n"; } int main() { Complex c1(3, 4), c2(5, -10), c3; c3 = c1.complex_add(c2); cout << "c1 = "; c1.print(); cout << "c2 = "; c2.print(); cout << "c1 + c2 = "; c3.print(); return 0; }
使用運算子過載:
#include <iostream> using namespace std; // 演示對運算子"+"進行過載達到目的! class Complex { public: Complex(); Complex(double r, double i); //帶引數的建構函式 Complex operator+(Complex &d); //運算子過載 void print(); private: double real; double imag; }; Complex::Complex() { real = 0; imag = 0; } Complex::Complex(double r, double i) { real = r; imag = i; } Complex Complex::operator+(Complex &d) { Complex c; c.real = real + d.real; c.imag = imag + d.imag; return c; } void Complex::print() { cout << "(" << real << "," << imag << "i)\n"; } int main() { Complex c1(3, 4), c2(5, -10), c3; c3 = c1 + c2; cout << "c1 = "; c1.print(); cout << "c2 = "; c2.print(); cout << "c1 + c2 = "; c3.print(); return 0; }
我們在宣告Complex類的時候對運算子進行了過載,使得這個類在使用者程式設計的時候可以完全不考慮函式是如何實現的,直接用+,-,*,/ 進行復數的運算即可。
其實還可以:
Complex Complex::operator+(Complex &2)
{
return Complex(real + c2.real, imag + c2.imag);
}
一些規則:
(1)C++不允許使用者自己定義新的運算子,只能對已有的C++運算子進行過載
(2)除了對以下運算子不允許過載外,其他運算子允許過載:
--- .(成員訪問運算子)
--- .*(成員指標訪問運算子)
--- ::(域運算子)
--- sizeof (尺寸運算子)
--- ?:(條件運算子)
(3) 過載不能改變運算子運算物件(運算元)個數
(4) 過載不能改變運算子的優先級別
(5) 過載不能改變運算子的結合性
(6) 過載運算子的函式不能有預設引數
(7) 過載運算子必須和使用者定義的自定義型別的物件一起使用,其引數至少應該有一個是類物件或類物件的引用。(也就是說,引數不能全部都是C++的標準型別,這樣約定是為了防止使用者修改用於標準型別結構的運算子性質)。
課後作業:
過載運算子"+","-","*","/"實現有理數的加減乘除運算。
有理數:任何可以用分數來表示的就是有理數