/*--------------------------------
功能:双目运算符重载为类的成员函数
运行结果:
2+3i
4+5i
6+8i
-2-2i
----------------------------------
Author: Zhang Kaizhou
Date: 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;
}
C++中将双目运算符重载为类的成员函数
最新推荐文章于 2021-12-19 23:48:58 发布