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

#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, const Rectangle& rec) // 这里的 const 是必要的,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;
}

  

posted @ 2019-12-01 10:22  路边的十元钱硬币  阅读(383)  评论(0编辑  收藏  举报