首页 > 编程语言 > 详细

C++_重载运算符<< 使自定义数据可以用cout输出

时间:2015-08-11 16:16:30      阅读:426      评论:0      收藏:0      [点我收藏+]

通过重载运算符<< 输出数据注意事项不能将返回的 ostream 加上const 限定,因为返回的 ostream流对象可能还会插入其他符号如endl 等等。

出错的片段

const ostream& operator<<(ostream &output, const Point &a){
	return output << a.x << " " << a.y ;
}
技术分享


正确的代码与完整测试程序:

#include <vector>
#include <iostream>

using namespace std;

struct Point{
	int x;
	int y;
};

ostream& operator<<(ostream &output, const Point &a){
	return output << a.x << " " << a.y ;
}

int main(){
	vector<Point> PointList;
	vector<Point>::iterator iter;
	//a[10] = 5;
	
	Point a;
	a.x = 5;
	a.y = 5;

	PointList.push_back(a);
	for (iter = PointList.begin(); iter < PointList.end(); iter++){
		cout << *iter << endl;
	}
	cout << "The sizeof vector<Point> PointList is ";
	cout << PointList.size() << endl;

	cout << 4 << endl;

	return 0;
}
测试输出
技术分享

版权声明:本文为博主原创文章,未经博主允许不得转载。

C++_重载运算符<< 使自定义数据可以用cout输出

原文:http://blog.csdn.net/u010003835/article/details/47420293

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!