首页 > 编程知识 正文

C 中将双目运算符重载为类的成员函数

时间:2023-05-04 18:23:08 阅读:226502 作者:4447

/*--------------------------------功能:双目运算符重载为类的成员函数运行结果:2+3i4+5i6+8i-2-2i----------------------------------Author: Zhang KaizhouDate: 2019-4-9 17:55:03--------------------------------*/#include <iostream>using namespace std;class Complex{ // 定义一个复数类private: double real; double imag;public: Complex(double r = 0.0, double i = 0.0):real(r), imag(i){} // 构造函数 Complex operator +(const Complex & c2) const; // 重载 + 号运算符 Complex operator -(const Complex & c2) const; // 重载 - 号运算符 void display() const;};Complex Complex::operator +(const Complex & c2) const{ // 形参为一个Complex类型的常引用变量 return Complex(real + c2.real, imag + c2.imag); // 返回一个临时的无名对象}Complex Complex::operator -(const Complex & c2) const{ return Complex(real - c2.real, imag - c2.imag);}void Complex::display() const{ cout << real; if(imag - 0.0 > 1e-8){ cout << "+" << imag << "i" << endl; }else{ cout << imag << "i" << endl; }}int main(){ Complex c1(2, 3), c2(4, 5), c3; c1.display(); c2.display(); c3 = c1 + c2; c3.display(); c3 = c1 - c2; c3.display(); return 0;}

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。