运算符重载是多态的一种方法。在 C++ 中,运算符重载被定义为将一个运算符用于不同的操作。例如,'+' 可以用于数学加法,同一个运算符也可以用于字符串连接。
这里我们将处理一个二元运算符(作用于两个操作数的运算符)“–”,其中一个操作数应作为参数传递给运算符函数。
创建一个名为 complex 的类。为 complex 类声明两个浮点型变量 real 和 imag。创建一个构造函数 complex 并将数据成员 real 和 imag 的值设置为 0。定义一个函数 input 以从用户读取变量 real 和 imag 的值。
创建运算符重载函数。这里创建了三个 complex 类型的对象(c1、c2、result)。将用户输入的值存储在变量 c1 和 c2(实部和虚部)中。定义一个函数来显示复数的实部和虚部。用户输入的复数之间的差将存储在对象 result 中。
步骤 1: 调用头文件 iostream。
步骤 2: 使用命名空间 std。
步骤 3: 创建一个包含浮点变量 real 和 imag 的 complex 类;
步骤 4: 创建一个构造函数 complex( ); 将 real 和 imag 的值设置为 0
步骤 5: 定义函数以从用户读取数字的实部和虚部。
步骤 6: 定义运算符重载函数。
步骤 7: 定义函数以显示复数的实部和虚部。
步骤 8: 为 complex 类创建三个对象:c1、c2 和 result;
步骤 9: 从用户读取数字并将它们存储在对象 c1 和 c2 中。C1.步骤 5 和 c2.步骤 5
步骤 10: 调用步骤 6 并将结果数字存储在对象 result 中;
步骤 11: 使用对象 result 调用步骤 7。result.步骤 7;
步骤 12: 退出
#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;
}
Enter first complex number: Enter real and imaginary parts respectively: 4 5 Enter second complex number: Enter real and imaginary parts respectively: 2 6 Output Complex number: 2-1i