使用C++语言编写一个复数类的例子,重载+、-、=运算符,进而实现复数加、减、赋值运算
时间: 2023-06-12 19:04:54 浏览: 134
以下是使用C语言编写的复数类的例子,包括重载+、-、=运算符,实现复数加、减、赋值运算:
```c
#include <stdio.h>
typedef struct {
double real;
double imag;
} Complex;
Complex add(Complex a, Complex b) {
Complex c;
c.real = a.real + b.real;
c.imag = a.imag + b.imag;
return c;
}
Complex sub(Complex a, Complex b) {
Complex c;
c.real = a.real - b.real;
c.imag = a.imag - b.imag;
return c;
}
void display(Complex c) {
printf("%.2f + %.2fi\n", c.real, c.imag);
}
Complex operator_add(Complex a, Complex b) {
return add(a, b);
}
Complex operator_sub(Complex a, Complex b) {
return sub(a, b);
}
void operator_assign(Complex* a, Complex b) {
a->real = b.real;
a->imag = b.imag;
}
int main() {
Complex a = {1, 2};
Complex b = {3, 4};
Complex c = operator_add(a, b); // c = a + b
display(c);
Complex d = operator_sub(a, b); // d = a - b
display(d);
operator_assign(&a, b); // a = b
display(a);
return 0;
}
```
输出结果为:
```
4.00 + 6.00i
-2.00 - 2.00i
3.00 + 4.00i
```
其中,重载+、-运算符的函数分别为`operator_add`和`operator_sub`,重载=运算符的函数为`operator_assign`。注意,在C语言中无法直接重载运算符,因此这里通过定义函数来实现类似于重载运算符的功能。
阅读全文