在定义复数类的基础上进行运算符的重载
时间: 2023-07-10 16:32:56 浏览: 41
好的,你想了解在定义复数类的基础上进行运算符的重载。在 C++ 中,我们可以通过运算符重载来定义自定义操作符的行为。在定义复数类时,我们可以重载一些运算符,例如加法运算符、减法运算符、乘法运算符等等。下面是一个示例:
```c++
#include<iostream>
using namespace std;
class Complex {
public:
double real;
double imag;
Complex(double r=0, double i=0):real(r), imag(i){}
Complex operator +(const Complex& c2) const {
return Complex(real+c2.real, imag+c2.imag);
}
Complex operator -(const Complex& c2) const {
return Complex(real-c2.real, imag-c2.imag);
}
Complex operator *(const Complex& c2) const {
return Complex(real*c2.real-imag*c2.imag, real*c2.imag+imag*c2.real);
}
};
int main()
{
Complex c1(1,2), c2(3,4);
Complex c3 = c1 + c2;
Complex c4 = c1 - c2;
Complex c5 = c1 * c2;
cout<<"c1+c2="<<c3.real<<"+"<<c3.imag<<"i"<<endl;
cout<<"c1-c2="<<c4.real<<"+"<<c4.imag<<"i"<<endl;
cout<<"c1*c2="<<c5.real<<"+"<<c5.imag<<"i"<<endl;
return 0;
}
```
在上面的代码中,我们定义了一个名为 Complex 的类,它有两个成员变量:实部和虚部。然后,我们重载了加法运算符、减法运算符和乘法运算符。在 main 函数中,我们创建了两个复数对象 c1 和 c2,然后使用重载后的加法、减法、乘法运算符对它们进行操作,并输出结果。
希望这个例子可以帮助你理解在定义复数类的基础上进行运算符的重载。