HDFS-HA搭建(一般用不到)
阿新 • • 發佈:2022-02-13
運算子過載分為類的成員運算子過載和非成員運算子過載;
類內成員運算子過載:
語法:
雙目運算子過載:
類名 operator運算子 (const 類名&);操作符的左運算元就是當前的物件,右運算元就是引數中的物件;
單目運算子過載:
自增自減運算子++、--;
①++或--在物件前面的情況:
類名& operator++ ();---這種情況下的過載沒有引數;
②++或者--在物件的後面的情況:
類名 operator++ (int);----這種情況下給過載操作符函式提供一個引數只是為了說明運算子在物件的後面;
舉例:
雙目運算子:
單目運算子:
非成員運算子過載:
語法類似,不過,引數列表為成員從左到右的順序,其中++和--的後置運算子例外,需額外加一個引數;
1 class Complex 2 { 3 double real; 4 double imag; 5 public: 6 Complex(double i = 0, double j = 0) : real(i), imag(j) {} 7 friend Complex operator+ (const Complex& c1, const Complex& c2); 8 friend Complex operator- (const Complex& c1, const Complex& c2); 9friend ostream& operator << (ostream& out, const Complex& complex); 10 friend Complex& operator++ (Complex& c1); 11 friend Complex operator++ (Complex& c1, int); 12 }; 13 14 Complex operator + (const Complex& c1, const Complex& c2) 15 { 16 returnComplex(c1.real + c2.real, c1.imag + c2.imag); 17 } 18 19 Complex operator - (const Complex& c1, const Complex& c2) 20 { 21 return Complex(c1.real - c2.real, c1.imag - c2.imag); 22 } 23 24 25 ostream& operator << (ostream& out, const Complex& complex) 26 { 27 out << complex.real << ", " << complex.imag << endl; 28 return out; 29 } 30 31 //++i 32 Complex& operator++ (Complex& c1) 33 { 34 c1.real++; 35 c1.imag++; 36 return c1; 37 } 38 39 //i++ 40 Complex operator++ (Complex& c1, int) 41 { 42 Complex complex; 43 complex = c1; 44 c1.real++; 45 c1.imag++; 46 return complex; 47 } 48 49 50 int main() 51 { 52 Complex complex1(2.0, 3.0), complex2(4, 5), complex3; 53 54 cout << complex1 << complex2 << complex3; 55 56 complex3 = complex1 + complex2; 57 cout << complex3; 58 59 complex3 = complex1 - complex2; 60 cout << complex3; 61 62 cout << ++complex3; 63 cout << complex3++; 64 65 cout << complex3; 66 67 68 return EXIT_SUCCESS; 69 }
宣告為友元函式僅僅為了能夠直接操作類的私有成員;
結果如下:
與預期相符;