首页 > 编程语言 > 详细

C++ class外的 << 重载,输出流,重载示例。不应该定义类内的<<重载

时间:2019-12-01 11:18:42      阅读:69      评论:0      收藏:0      [点我收藏+]
#include <iostream>

// overloading "operator << " outside class
// << 应该定义在类之外。

//////////////////////////////////////////////////////////

class Rectangle
{
public:
	Rectangle(int w, int h) 
		: width(w), height(h)
	{};

	~Rectangle() {};

public:
	int width;
	int height;
};


//////////////////////////////////////////////////////////

std::ostream&
operator<< (std::ostream& os, Rectangle& rec)
{
	os << rec.width << ", " << rec.height;
	return  os;

}


//////////////////////////////////////////////////////////

int main()
{
	Rectangle a(40, 10);
	Rectangle b(41, 11);
	Rectangle c(42, 12);

	std::cout
		<< "a = " << a << std::endl
		<< "b = " << b << std::endl
		<< "c = " << c << std::endl;

	return 0;
}

  

C++ class外的 << 重载,输出流,重载示例。不应该定义类内的<<重载

原文:https://www.cnblogs.com/alexYuin/p/11965232.html

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