【C++深度剖析教程11】C++学习之编写代码实现复数类
生活随笔
收集整理的這篇文章主要介紹了
【C++深度剖析教程11】C++学习之编写代码实现复数类
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
今天,我來學習將復數的加減乘除以及比較運算,編寫一個復數類,方便計算復數之間的運算。具體用的方法就是之前寫過的操作符重載的概念來實現(操作符重載的概念學習)。
那么為了顯得清晰,今天寫的程序運用模塊化的思想:
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); };#endifComplex.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; }main.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; }以上模塊代碼實現了,復數的四則運算法則以及比較的法則,運用了操作符重載的概念。代碼都可以通過鏈接直接下載得到源代碼下載鏈接碼云平臺。
注意事項:
總結:
- 復數的概念可以通過自定義類實現
- 復數中的運算操作可以通過操作符重載實現
- 賦值操作符只能通過廠原函數實現
- 操作符重載的本質為函數定義
想獲得各種學習資源以及交流學習的加我(有我博客中寫的代碼的原稿):
qq:1126137994
微信:liu1126137994
可以共同交流關于嵌入式,操作系統,C++語言,C語言,數據結構等技術問題。
總結
以上是生活随笔為你收集整理的【C++深度剖析教程11】C++学习之编写代码实现复数类的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 完整的qt安装教程
- 下一篇: python刷抖音_用Python生成抖