为复数类Complex重载+和-的操作,能实现复数的加减法,其中+用成员重载,-用友元重载,并在main函数中 验证其功能。
时间: 2024-11-18 18:17:54 浏览: 30
在C++中,我们可以为复数类Complex
重载+
和-
操作符,以便进行复数的加法和减法。+
操作符我们作为成员函数重载,而-
操作符作为友元函数重载。下面是一个简单的Complex
类的实现示例:
#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);
}
// 显示复数形式
void display() const {
cout << real << "+" << imag << "i" << endl;
}
// 友元函数重载:-
friend Complex operator-(const Complex& c) {
return Complex(-c.real, -c.imag);
}
};
int main() {
Complex c1(2, 3); // 复数1: 2 + 3i
Complex c2(4, -1); // 复数2: 4 - 1i
// 加法
Complex sum = c1 + c2;
sum.display(); // 输出: 6 + 2i
// 减法
Complex diff = c1 - c2;
diff.display(); // 输出: -2 + 4i
// 使用友元函数进行负数复数操作
Complex neg_c1 = -c1;
neg_c1.display(); // 输出: -2 - 3i
return 0;
}
在上述代码中,我们定义了Complex
类,包含两个私有成员变量real
和imag
表示实部和虚部。operator+
和operator-
分别重载为成员函数,实现了复数相加和相减。另外,我们还定义了一个友元函数operator-
,它接受一个Complex
类型的引用并返回其相反数。在main
函数中,我们创建了两个复数对象,并验证了加法和减法的结果。同时,我们也展示了如何使用友元函数对复数取反。