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

来源:互联网 发布:floyd算法详细解释 编辑:程序博客网 时间:2024/06/05 08:19

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

#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为输出内容不可更改加constfriend ostream & operator<<(ostream &os, const Complex &c){return os << "(" << c._x << "," << c._y << ")" << endl;}//因为是输入参数,所以可以更改参数&c 没有constfriend 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;}


阅读全文
0 0
原创粉丝点击