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; }
广告