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

      

  • 相关阅读:
    python知识点整理一
    Selenium之自动化常遇问题
    git学习
    哈,又是总结内容
    2.3返回IP地址(requests模块安装,get请求发送,loads 解析json到字典)
    2.2返回状态码的分类描述
    2.1JSON数据格式
    1.6file文件
    福利:字符串与字符编码
    1.5list中sort && sorted
  • 原文地址:https://www.cnblogs.com/alexYuin/p/11965972.html
Copyright © 2020-2023  润新知