#include using namespace std;

class Complex{ public: Complex(double r = 0, double i = 0):real(r), imag(i){} //构造函数 Complex operator-(const Complex &c); //重载运算符'-' friend Complex operator-(const Complex &c1, double c2); //友元函数,重载运算符'-' friend Complex operator-(double c1, const Complex &c2); //友元函数,重载运算符'-' void display(); //输出函数 private: double real, imag; };

Complex Complex::operator-(const Complex &c){ return Complex(real-c.real, imag-c.imag); }

Complex operator-(const Complex &c1, double c2){ return Complex(c1.real-c2, c1.imag); }

Complex operator-(double c1, const Complex &c2){ return Complex(c1-c2.real, -c2.imag); }

void Complex::display(){ cout << '(' << real << ',' << imag << ')' << endl; }

int main(){ Complex c1(3, 4), c2(1, 2), c3; c3 = c1 - c2; c3.display(); c3 = c1 - 2.5; c3.display(); c3 = 1.2 - c2; c3.display(); return 0; }

C++ 复数类 Complex 重载运算符 '-' 实现减法运算

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

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