用 C++ 程式過載加法運算子以加兩個複數
假設我們有一個帶實部和虛部的複數類。我們需要對加法(+)運算子進行過載,以便加兩個複數。我們還必須定義一個函式,以適當的表示形式返回複數。
因此,如果輸入類似於 c1 = 8 - 5i,c2 = 2 + 3i,則輸出將為 10 - 2i。
為了解決這個問題,我們將遵循以下步驟 −
過載 + 運算子並將另一個複數 c2 作為引數
定義一個名為 ret 的複數,其實部和虛部為 0
ret 的實部 := 自己的實部 + c2 的實部
ret 的虛部 := 自己的虛部 + c2 的虛部
返回 ret
示例
讓我們看看以下實現,以便更好地理解 −
#include <iostream>
#include <sstream>
#include <cmath>
using namespace std;
class Complex {
private:
int real, imag;
public:
Complex(){
real = imag = 0;
}
Complex (int r, int i){
real = r;
imag = i;
}
string to_string(){
stringstream ss;
if(imag >= 0)
ss << "(" << real << " + " << imag << "i)";
else
ss << "(" << real << " - " << abs(imag) << "i)";
return ss.str();
}
Complex operator+(Complex c2){
Complex ret;
ret.real = real + c2.real;
ret.imag = imag + c2.imag;
return ret;
}
};
int main(){
Complex c1(8,-5), c2(2,3);
Complex res = c1 + c2;
cout << res.to_string();
}
輸入
c1(8,-5), c2(2,3)
輸出
(10 - 2i)
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP