zoukankan      html  css  js  c++  java
  • 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;
    }
    

     

  • 相关阅读:
    块级作用域
    作用域变量 var
    unkown类型
    generator (2)
    generator (1)
    generator
    索引类型
    XML 特殊字符处理和 CDATA
    15 个实用的 PHP 正则表达式
    论MySQL数据库中两种数据引擎的差别
  • 原文地址:https://www.cnblogs.com/alexYuin/p/11965678.html
Copyright © 2011-2022 走看看