#include <iostream> using namespace std; class Complex { private: double real; // 复数的实部 double imag; // 复数的虚部 public: // 构造函数 Complex(double r = 0, double i = 0) : real(r), imag(i) {} // 成员函数 double getReal() const { return real; } double getImag() const { return imag; } void setReal(double r) { real = r; } void setImag(double i) { imag = i; } // 运算符重载 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); } Complex operator*(const Complex& c) const { return Complex(real * c.real - imag * c.imag, real * c.imag + imag * c.real); } Complex operator/(const Complex& c) const { double denominator = c.real * c.real + c.imag * c.imag; return Complex((real * c.real + imag * c.imag) / denominator, (imag * c.real - real * c.imag) / denominator); } Complex operator++() { return Complex(++real, ++imag); } Complex operator++(int) { return Complex(real++, imag++); } Complex operator--() { return Complex(--real, --imag); } Complex operator--(int) { return Complex(real--, imag--); } friend ostream& operator<<(ostream& os, const Complex& c); friend istream& operator>>(istream& is, Complex& c); }; // 友元函数,重载输出运算符 ostream& operator<<(ostream& os, const Complex& c) { os << c.real << "+" << c.imag << "i"; return os; } // 友元函数,重载输入运算符 istream& operator>>(istream& is, Complex& c) { is >> c.real >> c.imag; return is; } // 将 double 类型转换成复数类型 inline Complex doubleToComplex(double x) { return Complex(x, 0); } int main() { Complex c1(1, 2), c2(3, 4); cout << "c1 = " << c1 << endl; cout << "c2 = " << c2 << endl; cout << "c1 + c2 = " << c1 + c2 << endl; cout << "c1 - c2 = " << c1 - c2 << endl; cout << "c1 * c2 = " << c1 * c2 << endl; cout << "c1 / c2 = " << c1 / c2 << endl; cout << "++c1 = " << ++c1 << endl; cout << "--c2 = " << --c2 << endl; double d = 5.6; Complex c3 = doubleToComplex(d); cout << "c3 = " << c3 << endl; return 0; }对结果的说明
时间: 2024-03-04 22:52:11 浏览: 101
使用include <iostream>时一定要加using namespace std
这是一个 C++ 程序,定义了一个 Complex 类,实现了复数的基本运算(加、减、乘、除),以及自增自减运算符的重载。同时,还实现了友元函数重载输入输出运算符,以及一个将 double 类型转换成复数类型的 inline 函数。在 main 函数中,定义了三个复数对象,分别进行了各种运算,并输出了结果。最后,将一个 double 类型的变量转换成复数类型,并输出其值。
阅读全文