Skip to content

Latest commit

 

History

History
88 lines (63 loc) · 2.77 KB

File metadata and controls

88 lines (63 loc) · 2.77 KB

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

原文: https://www.programiz.com/cpp-programming/operator-overloading/binary-operator-overloading

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

要理解此示例,您应该了解以下 C++ 编程主题:


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


示例:用于减去复数的二元运算符重载

#include <iostream>
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 - c2时,会将c2作为参数传递给运算符。

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

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

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