c++ 实验要求:分别采用成员函数和友元函数重载实现复数的加法运算。
时间: 2024-03-24 20:39:06 浏览: 106
好的,为您提供具体的代码实现。
首先,我们需要定义一个复数类来存储复数的实部和虚部,示例代码如下:
```cpp
class Complex {
public:
Complex(double real = 0.0, double imag = 0.0) : m_real(real), m_imag(imag) {}
// 成员函数重载加法运算符
Complex operator+(const Complex& other) const {
return Complex(m_real + other.m_real, m_imag + other.m_imag);
}
// 声明友元函数
friend Complex operator+(const Complex& c1, const Complex& c2);
private:
double m_real; // 实部
double m_imag; // 虚部
};
```
这里我们为复数类定义了一个默认构造函数,以及一个成员函数重载加法运算符。
接下来,我们使用友元函数来实现复数的加法运算,示例代码如下:
```cpp
// 友元函数重载加法运算符
Complex operator+(const Complex& c1, const Complex& c2) {
return Complex(c1.m_real + c2.m_real, c1.m_imag + c2.m_imag);
}
```
在这个友元函数中,我们可以直接访问复数类的私有成员变量,从而实现复数的加法运算。
接下来,我们可以编写一个测试程序来验证我们的实现是否正确,示例代码如下:
```cpp
#include <iostream>
using namespace std;
int main() {
Complex c1(1.0, 2.0);
Complex c2(3.0, 4.0);
Complex c3 = c1 + c2; // 使用成员函数重载加法运算符
Complex c4 = operator+(c1, c2); // 使用友元函数重载加法运算符
cout << "c1 + c2 = " << c3.real() << " + " << c3.imag() << "i" << endl;
cout << "c1 + c2 = " << c4.real() << " + " << c4.imag() << "i" << endl;
return 0;
}
```
在这个测试程序中,我们分别使用了成员函数和友元函数重载加法运算符,并输出了计算结果。
这样,我们就完成了使用成员函数和友元函数重载实现复数的加法运算的实验要求。
阅读全文
相关推荐















