#include using namespace std;

class Complex { private: double real; double imag; public: Complex() { real = 0; imag = 0; } Complex(double r, double i) { real = r; imag = i; } double getReal() { return real; } double getImag() { return imag; } void setReal(double r) { real = r; } void setImag(double i) { imag = i; } Complex operator+(double d) { return Complex(real + d, imag); } friend ostream& operator<<(ostream& os, Complex c) { os << c.real << '+' << c.imag << 'i'; return os; } operator double() { return real; } };

int main() { Complex c(1, 2); double d = 3.14; double d1 = c + d; cout << "d1 = " << d1 << endl; Complex c1(d1, 0); cout << "c1 = " << c1 << endl; return 0; }

C++ 复数类:重载运算符实现复数与 double 型数相加

原文地址: https://www.cveoy.top/t/topic/nS1Y 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录