📜  C++程序使用运算符重载减去复数

📅  最后修改于: 2020-09-25 06:43:35             🧑  作者: Mango

在此示例中,您将学习使用- 运算符 运算符重载来减去复数。

由于-是二进制运算符(对两个操作数进行运算符 ),因此应将其中一个操作数作为参数传递给运算符 函数 ,其余过程类似于一元运算运算符的重载。

示例:二元运算符重载以减去复数

#include 
using namespace std;

class Complex
{
    private:
      float real;
      float imag;
    public:
       Complex(): real(0), imag(0){ }
       void input()
       {
           cout << "Enter real and imaginary parts respectively: ";
           cin >> real;
           cin >> imag;
       }

       // Operator overloading
       Complex operator - (Complex c2)
       {
           Complex temp;
           temp.real = real - c2.real;
           temp.imag = imag - c2.imag;

           return temp;
       }

       void output()
       {
           if(imag < 0)
               cout << "Output Complex number: "<< real << imag << "i";
           else
               cout << "Output Complex number: " << real << "+" << imag << "i";
       }
};

int main()
{
    Complex c1, c2, result;

    cout<<"Enter first complex number:\n";
    c1.input();

    cout<<"Enter second complex number:\n";
    c2.input();

    // In case of operator overloading of binary operators in C++ programming, 
    // the object on right hand side of operator is always assumed as argument by compiler.
    result = c1 - c2;
    result.output();

    return 0;
}

在该程序中,创建了三个Complex类型的对象,并要求用户输入存储在对象c1c2两个复数的实部和虚部。

然后执行语句result = c1 -c 2 。该语句调用运算符 函数 Complex operator - (Complex c2)

当执行result = c1 - c2c2作为参数传递给运算符 函数。

在C++编程中二进制运算符的运算符重载的情况下,编译器始终将运算符右侧的对象作为参数。

然后,此函数将所得的复数(对象)返回到显示在屏幕上的main() 函数 。

尽管本教程包含- 运算符的重载,但C++编程中的二进制运算符 (如+,*,<,+ =等)也可以以类似的方式进行重载。