用c++分别采用成员函数和友元函数重载实现复数的加法运算。
时间: 2024-02-28 12:56:09 浏览: 23
好的,让我来给您展示一下用C++分别采用成员函数和友元函数重载实现复数的加法运算的代码。
首先,我们定义一个复数类,包含实部和虚部两个私有成员变量:
```c++
class Complex {
private:
double real;
double imag;
public:
Complex(double real, double imag) {
this->real = real;
this->imag = imag;
}
void display() {
cout << real << " + " << imag << "i" << endl;
}
};
```
然后,我们用成员函数重载实现复数的加法运算:
```c++
class Complex {
private:
double real;
double imag;
public:
Complex(double real, double imag) {
this->real = real;
this->imag = imag;
}
void display() {
cout << real << " + " << imag << "i" << endl;
}
Complex operator+(Complex &other) {
Complex result(this->real + other.real, this->imag + other.imag);
return result;
}
};
```
最后,我们用友元函数重载实现复数的加法运算:
```c++
class Complex {
private:
double real;
double imag;
public:
Complex(double real, double imag) {
this->real = real;
this->imag = imag;
}
void display() {
cout << real << " + " << imag << "i" << endl;
}
friend Complex operator+(Complex &c1, Complex &c2) {
Complex result(c1.real + c2.real, c1.imag + c2.imag);
return result;
}
};
```
这样,我们就实现了用C++分别采用成员函数和友元函数重载实现复数的加法运算的代码。