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。达到链式的作用。

原文链接: https://www.cnblogs.com/mengfanrong/p/5171036.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    c++重载ostream的实现

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/228214

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月13日 下午1:52
下一篇 2023年2月13日 下午1:52

相关推荐