C++筆記 第三十一課 完善的複數類---狄泰學院
阿新 • • 發佈:2018-11-15
如果在閱讀過程中發現有錯誤,望評論指正,希望大家一起學習,一起進步。
學習C++編譯環境:Linux
第三十一課 完善的複數類
1.完善的複數類
複數類應該具有的操作
運算:+,-,*,/
比較:==,!=
賦值:=
求模:modulus
利用操作符過載
統一複數與實數的運算方式
統一複數與實數的比較方式
Complex 複數類的實現
Complex.h
#ifndef _COMPLEX_H_ //定義預處理巨集 #define _COMPLEX_H_ class Complex { double a;// 實部 double b;//虛部 public: //定義功能函式 Complex(double a = 0, double b = 0); double getA();//獲取實部 double getB(); double getModulus(); //定義操作符過載函式 Complex operator + (const Complex& c); Complex operator - (const Complex& c); Complex operator * (const Complex& c); Complex operator / (const Complex& c); //比較運算 bool operator == (const Complex& c); bool operator != (const Complex& c); //賦值操作符的過載,特殊之處在於只能當做成員函式實現 Complex& operator = (const Complex& c); }; #endif
Complex.cpp
#include "Complex.h" #include "math.h" //數學標頭檔案 Complex::Complex(double a, double b) { this->a = a; this->b = b; } double Complex::getA() { return a; } double Complex::getB() { return b; } double Complex::getModulus() { return sqrt(a * a + b * b); } Complex Complex::operator + (const Complex& c) { double na = a + c.a; double nb = b + c.b; Complex ret(na, nb); return ret; } Complex Complex::operator - (const Complex& c) { double na = a - c.a; double nb = b - c.b; Complex ret(na, nb); return ret; } Complex Complex::operator * (const Complex& c) { double na = a * c.a - b * c.b; double nb = a * c.b + b * c.a; Complex ret(na, nb); return ret; } Complex Complex::operator / (const Complex& c) { double cm = c.a * c.a + c.b * c.b; double na = (a * c.a + b * c.b) / cm; double nb = (b * c.a - a * c.b) / cm; Complex ret(na, nb); return ret; } bool Complex::operator == (const Complex& c) { return (a == c.a) && (b == c.b); } bool Complex::operator != (const Complex& c) { return !(*this == c);//特殊的計算 } Complex& Complex::operator = (const Complex& c) { if( this != &c )//檢視是否為同一個複數 { a = c.a; b = c.b; } return *this; }
工程進行階段性編譯,更好排除編譯錯誤
31-1.cpp
#include <stdio.h> #include "Complex.h" int main() { Complex c1(1, 2); Complex c2(3, 6); Complex c3 = c2 - c1; Complex c4 = c1 * c3; Complex c5 = c2 / c1; printf("c3.a = %f, c3.b = %f\n", c3.getA(), c3.getB()); printf("c4.a = %f, c4.b = %f\n", c4.getA(), c4.getB()); printf("c5.a = %f, c5.b = %f\n", c5.getA(), c5.getB()); Complex c6(2, 4); printf("c3 == c6 : %d\n", c3 == c6); printf("c3 != c4 : %d\n", c3 != c4); (c3 = c2) = c1; printf("c1.a = %f, c1.b = %f\n", c1.getA(), c1.getB()); printf("c2.a = %f, c2.b = %f\n", c2.getA(), c2.getB()); printf("c3.a = %f, c3.b = %f\n", c3.getA(), c3.getB()); return 0; } 執行結果: c3.a = 2.000000, c3.b = 4.000000 c4.a = -6.000000, c4.b = 8.000000 c5.a = 3.000000, c5.b = 0.000000 c3 == c6 : 1 c3 != c4 : 1 c1.a = 1.000000, c1.b = 2.000000 c2.a = 3.000000, c2.b = 6.000000 c3.a = 1.000000, c3.b = 2.000000
2.注意事項
C++規定賦值操作符(=)只能過載為成員函式
操作符過載不能改變原操作符的優先順序
操作符過載不能改變運算元的個數
操作符過載不能改變操作符的原有語義
小結
複數的概念可以通過自定義類實現
複數中的運算操作可以通過操作符過載實現
賦值操作符只能通過成員函式實現
操作符過載的本質為函式定義—擴充套件原有的功能