通过重载运算符<< 输出数据注意事项不能将返回的 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; }
测试输出
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-12-26 06:16:17