c++设计复数类,实现复数的加减乘除
时间: 2024-10-10 22:10:58 浏览: 40
在 C++ 中,设计一个复数类(ComplexNumber),可以包括两个私有成员变量分别代表实部(real)和虚部(imaginary)。我们可以使用结构体或类来封装这两个属性,并提供公共的构造函数、赋值操作符以及加法、减法、乘法和除法等运算方法。下面是一个简单的例子:
```cpp
#include <iostream>
// 定义复数类 ComplexNumber
class ComplexNumber {
private:
double real;
double imaginary;
public:
// 构造函数
ComplexNumber(double r = 0, double i = 0) : real(r), imaginary(i) {}
// 赋值操作符
ComplexNumber& operator=(const ComplexNumber& other) {
if (this != &other) {
real = other.real;
imaginary = other.imaginary;
}
return *this;
}
// 友元函数实现复数加法
friend ComplexNumber operator+(const ComplexNumber& a, const ComplexNumber& b) {
double real_sum = a.real + b.real;
double imag_sum = a.imaginary + b.imaginary;
return ComplexNumber(real_sum, imag_sum);
}
// 友元函数实现复数减法
friend ComplexNumber operator-(const ComplexNumber& a, const ComplexNumber& b) {
double real_diff = a.real - b.real;
double imag_diff = a.imaginary - b.imaginary;
return ComplexNumber(real_diff, imag_diff);
}
// 友元函数实现复数乘法
friend ComplexNumber operator*(const ComplexNumber& a, const ComplexNumber& b) {
double real_prod = a.real * b.real - a.imaginary * b.imaginary;
double imag_prod = a.real * b.imaginary + a.imaginary * b.real;
return ComplexNumber(real_prod, imag_prod);
}
// 友元函数实现复数除法,需要处理分母为0的情况
friend ComplexNumber operator/(const ComplexNumber& a, const ComplexNumber& b) {
double denominator = b.real * b.real + b.imaginary * b.imaginary;
if (denominator == 0) {
throw std::runtime_error("Division by zero is not allowed.");
}
double real_quotient = (a.real * b.real + a.imaginary * b.imaginary) / denominator;
double imag_quotient = (a.imaginary * b.real - a.real * b.imaginary) / denominator;
return ComplexNumber(real_quotient, imag_quotient);
}
// 打印复数
void print() const {
std::cout << real << " + " << imaginary << "i" << std::endl;
}
};
int main() {
ComplexNumber c1(3, 4);
ComplexNumber c2(1, 2);
c1.print(); // 输出 3 + 4i
c2.print(); // 输出 1 + 2i
ComplexNumber sum = c1 + c2;
ComplexNumber diff = c1 - c2;
ComplexNumber prod = c1 * c2;
ComplexNumber quot = c1 / c2; // 注意这里可能会抛出异常
sum.print();
diff.print();
prod.print();
try {
quot.print();
} catch (const std::exception& e) {
std::cerr << "Caught exception: " << e.what() << std::endl;
}
return 0;
}
```
在这个例子中,`operator+`, `operator-`, `operator*`, 和 `operator/` 都是友元函数,它们允许我们像对待普通值一样对复数进行操作。注意,在除法运算中需要特别处理分母为零的情况。
阅读全文