首页 > 编程语言 > 详细

C++ class 内的 [] 重载示例。

时间:2019-12-01 14:33:01      阅读:89      评论:0      收藏:0      [点我收藏+]
#include <iostream>

// overloading "operator [] " inside class

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

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

	~Rectangle() {};
	int& operator[] (const size_t i);

public:
	int width;
	int height;
};


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

int & 
Rectangle::operator[](const size_t i)
{
	if (i == 0)
		return width;
	else
		return height;
}


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

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

}

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

int main()
{
	Rectangle a(40, 10);
	
	std::cout
		<< "w = " << a[0] << std::endl		// 输出 40
		<< "h = " << a[1] << std::endl		// 输出 10
		;
	

	return 0;
}

 

C++ class 内的 [] 重载示例。

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

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