zoukankan      html  css  js  c++  java
  • C++ 的 +,加号重载示例

    #include <iostream>
    
    // overloading "operator + "
    // 要考虑加法的形式
    // a+1
    // a+a
    // 1+a
    
    //////////////////////////////////////////////////////////
    
    class Rectangle
    {
    public:
    	Rectangle(const int w, const int h) 
    		: width(w), height(h)
    	{};
    
    	~Rectangle() {};
    	Rectangle operator+ (const int& i) const;			// a+1,这里不能返回引用
    	Rectangle operator+ (const Rectangle& i) const;		// a+a
    														// 1+a,定义在class之外
    
    public:
    	int width;
    	int height;
    };
    
    
    //////////////////////////////////////////////////////////
    
    Rectangle
    Rectangle::operator+(const int& i) const				// a+1
    {
    	Rectangle r(*this);
    	r.width += i;
    	r.height += i;
    
    	return r;
    }
    
    Rectangle
    Rectangle::operator+(const Rectangle& rec) const		// a+a
    {
    	Rectangle r(*this);
    	r.width += rec.width;
    	r.height += rec.height;
    
    	return r;
    }
    
    
    //////////////////////////////////////////////////////////
    
    std::ostream&
    operator<< (std::ostream& os, const Rectangle& rec)
    {
    	os << rec.width << ", " << rec.height;
    	return  os;
    
    }
    
    
    Rectangle
    operator+(const int i, const Rectangle& rec)			// 1+a
    {
    	Rectangle r(rec);
    	r.width += i;
    	r.height += i;
    
    	return r;
    }
    
    
    //////////////////////////////////////////////////////////
    
    int main()
    {
    	Rectangle a(40, 10);
    	
    	std::cout << "a+1 = " << a + 1 << std::endl;
    	std::cout << "a+a = " << a + a << std::endl;
    	std::cout << "1+a = " << 1 + a << std::endl;
    
    
    	// 这种形式,先计算1+a,然后a+a,最后a+1。
    	std::cout
    		<< "a+1 = " << a + 1 << std::endl		
    		<< "a+a = " << a + a << std::endl		
    		<< "1+a = " << 1 + a << std::endl		
    		;
    	
    
    	return 0;
    }
    

      

  • 相关阅读:
    Web应用程序使用Hibernate
    Hibernate使用注释
    Hibernate入门程序
    Hibernate体系结构
    Spring MVC文件上传教程
    Spring MVC配置静态资源和资源包教程
    Spring MVC4使用Servlet3 MultiPartConfigElement文件上传实例
    Spring4 MVC文件下载实例
    Spring4 MVC+Hibernate4 Many-to-many连接表+MySQL+Maven实例
    Spring4 MVC+Hibernate4+MySQL+Maven使用注解集成实例
  • 原文地址:https://www.cnblogs.com/alexYuin/p/11965972.html
Copyright © 2011-2022 走看看