1.创建复数类complex,其中包含double型数据成员real和imag,分别表示复数的实域和虚域。为complex类重载运算符‘+’和‘-’,用来实现两个复数的加法和减法运算。要求用以下两种方法实现:重载函数为类的友元函数;重载函数为类的友元函数。
时间: 2024-02-21 11:58:11 浏览: 77
好的,我来解答你的问题。
首先是复数类的定义,包含实部和虚部两个成员变量,以及构造函数和输出函数:
```cpp
class complex {
public:
complex(double r = 0, double i = 0) : real(r), imag(i) {}
void print() const {
cout << real << "+" << imag << "i" << endl;
}
private:
double real, imag;
};
```
然后我们需要重载运算符‘+’和‘-’,可以使用友元函数或成员函数的方式来实现。
使用友元函数的方式:
```cpp
class complex {
public:
complex(double r = 0, double i = 0) : real(r), imag(i) {}
void print() const {
cout << real << "+" << imag << "i" << endl;
}
friend complex operator+(const complex& c1, const complex& c2);
friend complex operator-(const complex& c1, const complex& c2);
private:
double real, imag;
};
complex operator+(const complex& c1, const complex& c2) {
return complex(c1.real + c2.real, c1.imag + c2.imag);
}
complex operator-(const complex& c1, const complex& c2) {
return complex(c1.real - c2.real, c1.imag - c2.imag);
}
```
使用成员函数的方式:
```cpp
class complex {
public:
complex(double r = 0, double i = 0) : real(r), imag(i) {}
void print() const {
cout << real << "+" << imag << "i" << endl;
}
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);
}
private:
double real, imag;
};
```
使用时,可以这样调用:
```cpp
complex c1(1, 2), c2(3, 4);
complex c3 = c1 + c2;
c3.print(); // 输出 4+6i
complex c4 = c1 - c2;
c4.print(); // 输出 -2-2i
```
希望我的回答能够帮助你解决问题!
阅读全文