C++程式:使用運算子過載進行復數減法


在C++中,大多數內建運算子都可以進行運算子過載。過載的運算子是帶有關鍵字`operator`的函式,後跟定義的運算子符號。過載的運算子與任何函式一樣,都有返回型別和引數列表。

下面是一個使用運算子過載進行復數減法的程式:

示例

 線上演示

#include<iostream>
using namespace std;
class ComplexNum {
   private:
   int real, imag;
   public:
   ComplexNum(int r = 0, int i =0) {
      real = r;
      imag = i;
   }
   ComplexNum operator - (ComplexNum const &obj1) {
      ComplexNum obj2;
      obj2.real = real - obj1.real;
      obj2.imag = imag - obj1.imag;
      return obj2;
   }
   void print() {
      if(imag>=0)
      cout << real << " + i" << imag <<endl;
      else
      cout << real << " + i(" << imag <<")"<<endl;
   }
};
int main() {
   ComplexNum comp1(15, -2), comp2(5, 10);
   cout<<"The two comple numbers are:"<<endl;
   comp1.print();
   comp2.print();
   cout<<"The result of the subtraction is: ";
   ComplexNum comp3 = comp1 - comp2;
   comp3.print();
}

輸出

The two comple numbers are:
15 + i(-2)
5 + i10
The result of the subtraction is: 10 + i(-12)

在上面的程式中,定義了`ComplexNum`類,它分別具有表示複數實部和虛部的變數`real`和`imag`。`ComplexNum`建構函式用於初始化`real`和`imag`的值,幷包含預設值0。如下程式碼片段所示:

class ComplexNum {
   private:
   int real, imag;
   public:
   ComplexNum(int r = 0, int i =0) {
      real = r;
      imag = i;
   }
}

作為過載運算子的函式包含關鍵字`operator`,後跟`-`,因為這是要過載的運算子。該函式減去兩個複數,並將結果儲存在物件`obj2`中。然後將此值返回給`ComplexNum`物件`comp3`。

下面的程式碼片段演示了這一點:

ComplexNum operator - (ComplexNum const &obj1) {
   ComplexNum obj2;
   obj2.real = real - obj1.real;
   obj2.imag = imag - obj1.imag;
   return obj2;
}

`print()`函式列印複數的實部和虛部。如下所示。

void print() {
   if(imag>=0)
   cout << real << " + i" << imag <<endl;
   else
   cout << real << " + i(" << imag <<")"<<endl;
}

更新於:2020年6月24日

2K+瀏覽量

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告