c++复数运算符重载
时间: 2023-11-22 08:47:58 浏览: 145
C++复数运算符重载可以让我们自定义复数类型之间的运算,使得代码更加简洁易读。下面是一个复数类的例子,演示了如何重载加法运算符:
```c++
#include <iostream>
using namespace std;
class Complex {
private:
double real;
double imag;
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
Complex operator+(const Complex& c) {
return Complex(real + c.real, imag + c.imag);
}
void display() { cout << real << "+" << imag << "i" << endl; }
};
int main() {
Complex c1(3, 4), c2(5, 6), sum;
sum = c1 + c2;
sum.display(); // 输出:8+10i
return 0;
}
```
在上面的例子中,我们定义了一个复数类`Complex`,并重载了加法运算符`+`。在`operator+`函数中,我们定义了一个新的复数对象,其实部为两个复数对象的实部之和,虚部为两个复数对象的虚部之和。这样,我们就可以直接使用`+`运算符对两个复数对象进行相加了。
相关问题
c++复数类运算符重载
C++中的复数类可以通过运算符重载实现复数的加减乘除等运算。以下是一个示例代码,演示了如何重载复数类的运算符:
```c++
#include <iostream>
using namespace std;
class Complex {
private:
double real;
double imag;
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
Complex operator+(const Complex& other) const {
return Complex(real + other.real, imag + other.imag);
}
Complex operator-(const Complex& other) const {
return Complex(real - other.real, imag - other.imag);
}
Complex operator*(const Complex& other) const {
return Complex(real * other.real - imag * other.imag, real * other.imag + imag * other.real);
}
Complex operator/(const Complex& other) const {
double denominator = other.real * other.real + other.imag * other.imag;
return Complex((real * other.real + imag * other.imag) / denominator, (imag * other.real - real * other.imag) / denominator);
}
friend ostream& operator<<(ostream& os, const Complex& c) {
os << c.real << " + " << c.imag << "i";
return os;
}
};
int main() {
Complex c1(1, 2);
Complex c2(3, 4);
cout << "c1 = " << c1 << endl;
cout << "c2 = " << c2 << endl << endl;
cout << "c1 + c2 = " << c1 + c2 << endl;
cout << "c1 - c2 = " << c1 - c2 << endl;
cout << "c1 * c2 = " << c1 * c2 << endl;
cout << "c1 / c2 = " << c1 / c2 << endl;
return 0;
}
```
在上述代码中,我们重载了复数类的加、减、乘、除四个运算符,通过重载运算符实现了复数的运算。同时,我们还重载了输出运算符,用于输出复数对象的值。
c++不用运算符重载进行复数加减法
在 C++ 中,可以使用结构体或类来表示复数,然后定义成员函数实现加减法运算。以下是一个示例代码:
```c++
#include <iostream>
using namespace std;
struct Complex {
double real, imag;
Complex(double r = 0.0, double i = 0.0): real(r), imag(i) {}
Complex operator+(const Complex& c) const {
return Complex(real + c.real, imag + c.imag);
}
Complex operator-(const Complex& c) const {
return Complex(real - c.real, imag - c.imag);
}
void display() const {
cout << "(" << real << ", " << imag << "i)" << endl;
}
};
int main() {
Complex c1(1.0, 2.0);
Complex c2(3.0, 4.0);
Complex c3 = c1 + c2;
Complex c4 = c1 - c2;
c3.display();
c4.display();
return 0;
}
```
在上面的代码中,定义了一个结构体 Complex,其中包含实部和虚部两个成员变量,以及加减法运算符重载的成员函数。在主函数中,创建了两个复数对象 c1 和 c2,并分别进行加减法运算,将结果保存到 c3 和 c4 中,并输出结果。
阅读全文