C++1.创建复数类complex,其中包含double型数据成员real和imag,分别表示复数的实域和虚域。为complex类重载运算符‘+’和‘-’,用来实现两个复数的加法和减法运算。要求用以下两种方法实现:重载函数为类的友元函数;重载函数为类的友元函数。
时间: 2024-02-21 15:59:09 浏览: 61
c.rar_class Complex_show_编写一个C ++类
5星 · 资源好评率100%
1. 重载函数为类的成员函数:
```c++
#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& c) const; // 加法运算符重载
complex operator-(const complex& c) const; // 减法运算符重载
void display() const;
};
complex complex::operator+(const complex& c) const {
return complex(real + c.real, imag + c.imag);
}
complex complex::operator-(const complex& c) const {
return complex(real - c.real, imag - c.imag);
}
void complex::display() const {
cout << real << " + " << imag << "i" << endl;
}
int main() {
complex c1(1, 2);
complex c2(3, 4);
complex c3 = c1 + c2; // 调用重载的+运算符
complex c4 = c1 - c2; // 调用重载的-运算符
c3.display();
c4.display();
return 0;
}
```
2. 重载函数为类的友元函数:
```c++
#include <iostream>
using namespace std;
class complex {
private:
double real;
double imag;
public:
complex(double r = 0, double i = 0): real(r), imag(i) {}
friend complex operator+(const complex& c1, const complex& c2); // 加法运算符重载
friend complex operator-(const complex& c1, const complex& c2); // 减法运算符重载
void display() const;
};
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);
}
void complex::display() const {
cout << real << " + " << imag << "i" << endl;
}
int main() {
complex c1(1, 2);
complex c2(3, 4);
complex c3 = c1 + c2; // 调用重载的+运算符
complex c4 = c1 - c2; // 调用重载的-运算符
c3.display();
c4.display();
return 0;
}
```
两种方法都可以实现复数类的加减运算符重载,其中重载函数为类的成员函数需要使用成员函数的形式来调用运算符,而重载函数为类的友元函数则可以直接使用运算符符号来调用。
阅读全文