输入输出流重载.cpp

来自「c++实例~ 初学基础」· C++ 代码 · 共 46 行

CPP
46
字号
#include<iostream.h>

class complex
{
private:
	double real;
	double imag;
public:
	complex(double r=0,double i=0)
	{
		real=r;
		imag=i;
	}
	friend ostream & operator << (ostream &,complex &);
	friend istream & operator >> (istream &,complex &);
};
ostream & operator << (ostream & out,complex & c)
{
	out<<c.real;
	if(c.imag>0)
		out<<"+";
	if(c.imag!=0)
		out<<c.imag<<"i";
	return out;
}
istream & operator >> (istream & in,complex & c)
{
	cout<<"Input the real of the complex: "<<endl;
	in>>c.real;
	cout<<"Input the imagine of the complex: "<<endl;
	in>>c.imag;
	return in;
}
void main()
{
	complex c1(2.5,3.7);
	complex c2(8.2,-7.4);
	cout<<"The value of c1 is: "<<c1<<endl;
	cout<<"The value of c2 is: "<<c2<<endl;
	complex c3;
	cin>>c3;
	cout<<"The value of c3 is: "<<c3<<endl;
	return;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?