C++定义一个复数类,用友元函数实现对双目运算符“+”的运算符重载,使其 适用于复数运算。
时间: 2023-03-14 22:24:00 浏览: 111
C++运算符重载函数作为类成员函数和友元函数.docx
我可以给你一个参考的示例:class Complex {public: double re; // real part double im; // imaginary part Complex(double re, double im) : re(re), im(im) {}; // constructor Complex operator+(const Complex& c) {return Complex(this->re + c.re, this->im + c.im);}; // overload + operator Complex operator-(const Complex& c) {return Complex(this->re - c.re, this->im - c.im);}; // overload - operator Complex operator*(const Complex& c) {return Complex(this->re * c.re - this->im * c.im, this->re * c.im + this->im * c.re);}; // overload * operator Complex operator/(const Complex& c) {return Complex((this->re * c.re + this->im * c.im) / (c.re * c.re + c.im * c.im), (this->im * c.re - this->re * c.im) / (c.re * c.re + c.im * c.im));}; // overload / operator};
阅读全文