c++重载ostream的实现

#include <iostream>
using namespace std;

class Point{
public:
	Point(int _x = 0, int _y = 0, int _z = 0):x(_x), y(_y), z(_z){}
	Point(){}
	~Point(){}
	friend ostream& operator<<(ostream &os, const Point &pd);
private:
	int x;
	int y;
	int z;
};

ostream& operator<<(ostream &os, const Point &pd){
	os << pd.x<<" "<<pd.y<<" "<<pd.z;
	return os;
}
 
int main() {
	Point pd(1,2,3);
	cout<<pd;
	return 0;
}
基本的注意点就是。要把函数作为class Point的友元函数,在类的外面进行定义,此外要注意return os。达到链式的作用。
posted @ 2016-01-30 14:34  mengfanrong  阅读(1586)  评论(0)    收藏  举报
众安尊享e升2025版 - 底部横幅广告
尊享e升 2025版
🚀 全新升级
百万医疗险全面升级 守护健康人生
✓ 一般医疗300万
✓ 重疾600万
✓ 6年保证续保
✓ 1万免赔额
600万
最高保障
首月特惠价
低至1元起
🛡️ 立即投保