復數類重載加法、減法和乘法運算符


以下定義了一個復數類及其部分實現,現要求將類的構造函數以及運算符+、- 和 * 函數重載補充完整。

復數類定義:

在這里描述復數類定義。具體如下:
class complex {
	public:
		complex(float r=0,float i=0);                   // 構造函數
		complex operator+(const complex &op2) const;    //重載運算符 +
		complex operator-(const complex &op2) const;    //重載運算符 -
		complex operator*(const complex &op2) const;    //重載運算符 *
		void display() const;                           // 按數學寫法輸出復數
	private:
		float real;
		float imag;
};
 

裁判測試程序樣例:

在這里給出復數類測試的例子。例如:
#include <iostream>
using namespace std;
class complex {
	public:
		complex(float r=0,float i=0);                   // 構造函數
		complex operator+(const complex &op2) const;    //重載運算符 +
		complex operator-(const complex &op2) const;    //重載運算符 -
		complex operator*(const complex &op2) const;    //重載運算符 *
		void display() const;                           // 按數學寫法輸出復數
	private:
		float real;
		float imag;
};

/* ------------------- 請在這里填寫答案-------------------- */

void complex::display() const {
if(real&&imag)
if(imag1||imag-1)
cout<<real<<(imag>0?"+":"-")<<"i"<<endl;
else
cout<<real<<(imag>0?"+":"")<<imag<<"i"<<endl;
else if(real)
cout<<real<<endl;
else if (imag)
if(imag1||imag-1)
cout<<(imag>0?"":"-")<<"i"<<endl;
else
cout<<imag<<"i"<<endl;
else
cout<<0<<endl;
}

int main() {
double real,imag;
complex c,d,e;

<span class="hljs-built_in">cin</span>&gt;&gt;real&gt;&gt;imag;
<span class="hljs-function"><span class="hljs-built_in">complex</span> <span class="hljs-title">c1</span><span class="hljs-params">(real,imag)</span></span>;
<span class="hljs-built_in">cin</span>&gt;&gt;real&gt;&gt;imag;
<span class="hljs-function"><span class="hljs-built_in">complex</span> <span class="hljs-title">c2</span><span class="hljs-params">(real,imag)</span></span>;

c=c1+c2;
d=c1-c2;
e=c1*c2;
c.<span class="hljs-built_in">display</span>() ;
d.<span class="hljs-built_in">display</span>() ;
e.<span class="hljs-built_in">display</span>();

<span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;

}

輸入樣例:

在這里給出一組輸入。例如:

2 3
-4 -5
 

輸出樣例:

在這里給出相應的輸出。例如:

-2-2i
6+8i
7-22i
 

正確代碼:

complex::complex(float r,float i){
    real = r;
    imag = i;
}
complex complex::operator+(const complex &op2) const{
    complex temp;
    temp.imag = this->imag + op2.imag;
    temp.real = this->real + op2.real;
    return temp;
}
complex complex::operator-(const complex &op2) const{
    complex temp;
    temp.imag = this->imag - op2.imag;
    temp.real = this->real - op2.real;
    return temp;
}
complex complex::operator*(const complex &op2) const{
    complex temp;
    temp.imag = this->imag * op2.real+this->real*op2.imag;
    temp.real = this->real * op2.real-this->imag*op2.imag;
    return temp;
}   


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM