编写一个C++程序要求实现:1. 类的定义,构造函数,成员函数 2.两个复数运算的运算符重载.重载 +、-、*、/、++、--、<<、>>等运算符 3. double型数可以转换成复数
时间: 2023-07-10 14:38:40 浏览: 100
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& c2) const{ // 加法重载
return Complex(real + c2.real, imag + c2.imag);
}
Complex operator - (const Complex& c2) const{ // 减法重载
return Complex(real - c2.real, imag - c2.imag);
}
Complex operator * (const Complex& c2) const{ // 乘法重载
return Complex(real * c2.real - imag * c2.imag, real * c2.imag + imag * c2.real);
}
Complex operator / (const Complex& c2) const{ // 除法重载
double denominator = c2.real * c2.real + c2.imag * c2.imag;
return Complex((real * c2.real + imag * c2.imag) / denominator, (imag * c2.real - real * c2.imag) / denominator);
}
Complex operator ++ () { // 前置自增运算符重载
++real;
return *this;
}
Complex operator -- () { // 前置自减运算符重载
--real;
return *this;
}
Complex operator ++ (int) { // 后置自增运算符重载
Complex temp = *this;
real++;
return temp;
}
Complex operator -- (int) { // 后置自减运算符重载
Complex temp = *this;
real--;
return temp;
}
friend ostream& operator << (ostream& out, const Complex& c){ // 输出运算符重载
out << c.real << "+" << c.imag << "i";
return out;
}
friend istream& operator >> (istream& in, Complex& c){ // 输入运算符重载
cout << "请输入实部和虚部:";
in >> c.real >> c.imag;
return in;
}
operator double() const{ // double转Complex运算符重载
return real;
}
};
int main(){
Complex c1(1, 2), c2(3, 4);
cout << "c1 = " << c1 << endl;
cout << "c2 = " << c2 << endl;
Complex c3 = c1 + c2;
cout << "c1 + c2 = " << c3 << endl;
Complex c4 = c1 - c2;
cout << "c1 - c2 = " << c4 << endl;
Complex c5 = c1 * c2;
cout << "c1 * c2 = " << c5 << endl;
Complex c6 = c1 / c2;
cout << "c1 / c2 = " << c6 << endl;
++c1;
cout << "++c1 = " << c1 << endl;
--c1;
cout << "--c1 = " << c1 << endl;
c1++;
cout << "c1++ = " << c1 << endl;
c1--;
cout << "c1-- = " << c1 << endl;
double d = 5.6;
Complex c7 = d;
cout << "c7 = " << c7 << endl;
Complex c8;
cin >> c8;
cout << "c8 = " << c8 << endl;
return 0;
}
```
这个程序定义了一个 `Complex` 类,其中包含了 `real` 和 `imag` 两个私有成员变量,代表复数的实部和虚部。
程序中重载了加减乘除、前置后置自增自减、输出和输入运算符,实现了复数的基本运算和输出输入功能。
此外还重载了一个运算符,将 `double` 类型的数转换成 `Complex` 类型。
在 `main` 函数中,我们创建了两个 `Complex` 类型的对象 `c1` 和 `c2`,并对它们进行了加减乘除、自增自减、输出输入等操作。
阅读全文