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

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


Since - 是一个二元运算符(对两个操作数进行操作的运算符),其中一个操作数应作为参数传递给运算符函数,其余处理方式与一元运算符重载类似。


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

#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 - c2。此语句会调用运算符函数 Complex operator - (Complex c2)

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

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

然后,此函数将结果复数(对象)返回给 main() 函数,并在屏幕上显示。

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

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战