流输入>>、流输出<<作为友元重载

流输入>>、流输出<< 作为友元重载

#include "stdafx.h"
#include <iostream>
using namespace std;

//流输入输出重载

class Complex
{
public:
	Complex(float x = 0, float y = 0)
		:_x(x), _y(y){}
	void dis()
	{
		cout << "(" << _x << "," << _y << ")" << endl;
	}

	//cout<<c<<c; 可以连续输入也就是将 第一次的结果返回并作为左边参数 
	//所以返回类型为ostream 而且对象没有消失所以为&
	//而参数 &c为输出内容不可更改加const
	friend ostream & operator<<(ostream &os, const Complex &c)
	{
		return os << "(" << c._x << "," << c._y << ")" << endl;

	}

	//因为是输入参数,所以可以更改参数&c 没有const
	friend istream & operator>>(istream &is,  Complex &c)
	{
		return is >> c._x >> c._y;
	}

private:
	float _x;
	float _y;
};


int _tmain(int argc, _TCHAR* argv[])
{
	Complex c(1, 2), c1(2, 3);
	//cin >> c;

	operator>>(cin, c);

	cout << c << c1 << endl;

	operator<<(operator<<(cout, c), c1) << endl;

	//a+b;  做成员 a.operator+(b)  cout.operator<<(c)
	//因为cout对象是标准库里面的 不能更改 所以不能做成员

	//      做友元 operator+(a,b) operator<<(cout,c)

	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值