📄 demo_operator_02_e.cpp
字号:
//************************************************
// 定义复数类,重载运算符为类的成员函数
// 重载二元运算符加"+",减"-",赋值"="
// 重载一元运算符求负"-"
//************************************************
# include <iostream.h>
class Complex
{
public:
Complex(double r=0,double i=0);
Complex(const Complex & other);
void display();
Complex operator + (const Complex & other);
Complex operator - (const Complex & other);
Complex operator - ();
Complex operator = (const Complex & other);
protected:
double real,image;
};
Complex::Complex(double r,double i)
{
real=r;
image=i;
return;
}
Complex::Complex(const Complex & other)
{
real=other.real;
image=other.image;
return;
}
void Complex::display()
{
cout<<real;
if(image>0) cout<<"+"<<image<<"i";
if(image<0) cout<<image<<"i";
cout<<endl;
return;
}
Complex Complex::operator + (const Complex & other)
{
Complex temp;
temp.real=real+other.real;
temp.image=image+other.image;
return temp;
}
Complex Complex::operator - (const Complex & other)
{
Complex temp;
temp.real=real-other.real;
temp.image=image-other.image;
return temp;
}
Complex Complex::operator - ()
{
Complex temp;
temp.real=-real;
temp.image=-image;
return temp;
}
Complex Complex::operator = (const Complex & other)
{
real=other.real;
image=other.image;
return *this;
}
int main()
{
Complex c1(1,2),c2(2),c3(c1);
c1.display();
c2.display();
c3.display();
c1=c1+c2+c3;
c1.display();
c2=-c3;
c2.display();
c3=c2-c1;
c3.display();
return 0;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -