可以使用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<<"这两个补码是:"<<endl; comp1.print(); comp2.print(); cout<<"The result of the subtraction is: "; ComplexNum comp3 = comp1 - comp2; comp3.print(); }
输出结果
这两个补码是: 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; } }
作为重载运算符的函数包含关键字运算符,后跟-,因为这是被重载的运算符。该函数将两个复数相减,结果存储在对象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; }