c++输入输出流运算符的重载

说明:输入输出运算符的重载必须为友元函数,并且必须有输入输出流的返回值,固定格式为:

friend istream& operator >> (istream&, 重载类名&);

 

friend ostream& operator << (ostream&,重载类名&);

测试代码:

#include
using namespace std;
class Complex
{
public:
	void display();
	Complex operator + (Complex B);

	friend istream & operator>>(istream &,Complex&);
	friend ostream & operator<<(ostream &, Complex&);

	Complex(double real = 0.0, double image = 0.0)
	{
		this->real = real, this->image = image;
	}
	~Complex(void);
	
private:
	double real;
	double image;
};
void Complex::display() {
	cout << real;
	if (image > 0)
		cout << " + ";
	cout << image << "i"<real + B.real, this->image + B.image);
}

istream & operator>>(istream & input, Complex& A)
{
	input >> A.real >> A.image;
	return input;
}
ostream & operator<<(ostream & output, Complex&A)
{
	output << A.real;
	if (A.image > 0) output << "+";
	output << A.image << "i";
	return output;
}
int main()
{
	Complex A(1,2);
	Complex B(3, 4);
	cin >> A;
	A.display();
	B.display();
	(A + B).display();
	return 0;
}

你可能感兴趣的:(c++)