为了更好地理解此 C++ 程序示例,我们始终建议您学习以下列出的 C++ 编程基础主题
复数的概念由一位希腊数学家在公元 1 世纪引入。
如果一个数包含实部和虚部,则认为它是一个复数。我们可以用 z = x + iy 的形式表示一个复数。简单来说,我们可以说一个由实数和虚部组合而成的数称为复数。
此处,
让我们举一个例子,5 + 8i 是一个复数,其中 5 是实数,8i 是虚数。复数的实际用途是表示周期性运动,如光波、电流波和水波。
运算符重载是 多态性 中的一种方法。在 C++ 中,运算符 重载 定义为将一个运算符用于不同的操作。例如,'+' 可以用于加法,同一个运算符也可以用于字符串连接。
在 C++ 程序中,我们将处理二元运算符(作用于两个操作数的运算符)‘+’。
创建一个类 complex。为类 complex 声明两个浮点型变量 real 和 imag。创建一个构造函数 complex 并将数据成员 real 和 imag 的值设置为 0。定义一个函数 input 以从用户读取变量 real 和 imag 的值。
为运算符重载创建函数。这里创建了三个 complex 类型的对象(c1, c2, result)来存储用户输入到变量 c1 和 c2(实部和虚部值)中的值。定义一个函数来显示复数的实部和虚部。用户输入的复数之和将存储在对象 result 中。
步骤 1:调用头文件 iostream.
步骤 2:使用 namespace std。
步骤 3:创建一个类 complex,包含浮点型变量 real 和 imag;
步骤 4:创建一个构造函数 complex( );将 real 和 imag 的值设置为 0
步骤 5: 定义函数以从用户读取数字的实部和虚部。
步骤 6:定义一个运算符重载函数。
步骤 7: 定义一个函数来显示复数的实部和虚部。
步骤 8:为类 complex 创建三个对象,c1, c2, 和 result;
步骤 9:从用户读取数字并将其存储在对象 c1 和 c2 中。C1.步骤 5 和 c2.步骤 5
步骤 10: 调用步骤 6 并将结果数字存储在对象 result 中;
步骤 11: 调用步骤 7,使用对象 result.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: 2 8 Enter second complex number: Enter real and imaginary parts respectively: 4 3 Output Complex number: 6+11i