📄 demo_operator_07_b.cpp
字号:
//************************************************
// 复数类的定义和使用
//************************************************
# include <iostream.h>
class Complex
{
public:
Complex(double r=0,double i=0);
Complex(const Complex & other);
Complex operator + (const Complex & other);
Complex operator - (const Complex & other);
Complex operator - ();
Complex operator = (const Complex & other);
friend ostream & operator << (ostream & sream,Complex obj);
friend istream & operator >> (istream & sream,Complex & obj);
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;
}
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;
}
ostream & operator << (ostream & stream,Complex obj)
{
stream<<obj.real;
if(obj.image>0) stream<<"+"<<obj.image<<"i";
if(obj.image<0) stream<<obj.image<<"i";
return stream;
}
istream & operator >> (istream & stream,Complex & obj)
{
cout<<"Input real part:";
stream>>obj.real;
cout<<"Input image part:";
stream>>obj.image;
return stream;
}
int main()
{
Complex c1,c2;
cout<<"Input the first complex number c1:"<<endl;
cin>>c1;
cout<<"Input the second complex number c1:"<<endl;
cin>>c2;
cout<<"c1 is: "<<c1<<endl;
cout<<"c2 is: "<<c2<<endl;
cout<<"c1+c2 is: "<<c1+c2<<endl;
cout<<"c1-c2 is: "<<c1-c2<<endl;
return 0;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -