zoukankan      html  css  js  c++  java
  • C++ class内的 < 和 > 重载,大于号,小于号,重载示例。

    #include <iostream>
    
    // overloading "operator = " outside class
    // < 和 > 是二元操作符
    
    //////////////////////////////////////////////////////////
    
    class Rectangle
    {
    public:
    	Rectangle(int w, int h) 
    		: width(w), height(h)
    	{};
    
    	~Rectangle() {};
    
    
    	bool operator< (Rectangle& rec);//注意比较的顺序。this是被比的对象。
    	bool operator> (Rectangle& rec);
    
    
    
    public:
    	int width;
    	int height;
    };
    
    
    bool
    Rectangle::operator< (Rectangle & rec)//相同的class对象互为友元,所以可以访问private对象。< 是二元操作符,class内隐藏了this
    {
    	return this->height * this->width < rec.height * rec.width;
    }
    
    bool
    Rectangle::operator> (Rectangle & rec)//二元操作符,class内隐藏了this
    {
    	return !(*this < rec);
    }
    
    //////////////////////////////////////////////////////////
    
    int main()
    {
    	Rectangle a(40, 10);
    	Rectangle b(40, 56);
    
    	std::cout << (a < b) << std::endl;
    	std::cout << (a > b) << std::endl;
    
    	return 0;
    }
    

      

  • 相关阅读:
    iOS开发系列-Category
    OC开发系列-内存管理
    OC开发系列-@property和@synthesize
    OC开发系列-成员变量的作用域
    OC开发系列-类与对象
    MySQL
    JavaWeb
    POJ1845-Sumdiv大数约数和
    poj1159 Palindrome 区间DP
    poj 2955 Brackets 区间DP
  • 原文地址:https://www.cnblogs.com/alexYuin/p/11965190.html
Copyright © 2011-2022 走看看