zoukankan      html  css  js  c++  java
  • C++ class 内的 () 重载示例

    #include <iostream>
    
    // overloading "operator () " outside 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;
    }
    

      

  • 相关阅读:
    JAVA类型之间的转换
    Mysql语句
    Tomcat 优化
    JVM原理及调优
    static
    指针与引用
    sizeof
    遇到问题:c++ 直接cout输出char类型变量地址乱码
    编程过程中全面考虑问题的能力
    表、栈和队列
  • 原文地址:https://www.cnblogs.com/alexYuin/p/11965912.html
Copyright © 2011-2022 走看看