定義一個復數類complex重載運算符+使之能(定義一個復數類complex重載運算符)

博主:yunbaotangyunbaotang 2023-12-09 469 0條評論
摘要: 您好,今天小編胡舒來為大家解答以上的問題。定義一個復數類complex重載運算符+使之能,定義一個復數類complex重載運算符相信很多小伙伴還不知道,現在讓我們一起來看看吧!1、...

您好,今天小編胡舒來為大家解答以上的問題。定義一個復數類complex重載運算符+使之能,定義一個復數類complex重載運算符相信很多小伙伴還不知道,現在讓我們一起來看看吧!

1、#include using namespace std;class CComplex{ private: float real, image; public: CComplex() { } CComplex( float r, float img ) { real = r; image = img; } CComplex( CComplex& another ) { real = another.real; image = another.image; } CComplex &operator = (CComplex &another ) { real = another.real; image = another.image; return *this; } CComplex operator +( CComplex & another ) { return CComplex( real+ another.real, image + another.image ); } CComplex operator -( CComplex & another ) { return CComplex( real- another.real, image - another.image ); } CComplex operator *( CComplex & another ) { CComplex prod; //prod = *this; prod.real = real*another.real - image*another.image; prod.image = real*another.image + image*another.real; return prod; //return CComplex( real+ another.real, image + another.image ); } CComplex operator /( CComplex & another ) { CComplex quot; float sq = another.real*another.real + another.image*another.image; quot.real = (real*another.real + image*another.image)/sq; quot.image = (image*another.real - real*another.image)/sq; return quot; }};void main(){ CComplex c1( 2, 3 ), c2( 3, 3 ); CComplex c4, c5, c6, c7; c4 = c1 + c2; c5 = c1 - c2; c6 = c1*c2; c7 = c1/c2;}。

本文就為大家分享到這里,希望小伙伴們會喜歡。