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


    #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;
    }
    

     

  • 相关阅读:
    elastic
    原生js获取css样式和修改css样式
    React项目开发中的数据管理
    js获取鼠标位置
    闭包
    HTML5与HTML4的区别
    JSON 相关
    RESTful Web Services初探
    IE6浏览器兼容问题及部分解决方案
    关于Doctype
  • 原文地址:https://www.cnblogs.com/alexYuin/p/11965678.html
Copyright © 2020-2023  润新知