zoukankan      html  css  js  c++  java
  • C++ class内的==重载,判断相等,测试等于,重载示例。二元操作符

    #include <iostream>
    
    // overloading "operator == " inside class
    // == 是二元操作符
    
    
    //////////////////////////////////////////////////////////
    
    class Rectangle
    {
    public:
    	Rectangle(int w, int h) 
    		: width(w), height(h)
    	{};
    
    	~Rectangle() {};
    
    	bool operator == (Rectangle& rec) const;
    
    
    private:
    	int width;
    	int height;
    };
    
    //////////////////////////////////////////////////////////
    
    bool Rectangle::operator==(Rectangle & rec) const//相同的class对象互为友元,所以可以访问private对象。== 是二元操作符,class内隐藏了this
    {
    	return this->height == rec.height
    		&& this->width == rec.width;
    }
    
    // 等价于:
    /*
    bool Rectangle::operator==(Rectangle* this, Rectangle & rec) const
    {
    	return this->height == rec.height
    		&& this->width == rec.width;
    }
    */
    
    //////////////////////////////////////////////////////////
    
    int main()
    {
    	Rectangle a(40, 10);
    	Rectangle b(40, 10);
    	Rectangle c(4, 10);
    
    	std::cout << (a == b) << std::endl;
    	std::cout << (a == c) << std::endl;
    	std::cout << (b == c) << std::endl;
    
    	return 0;
    }
    

      

  • 相关阅读:
    TypeScript入门
    github个人博客绑定单独阿里域名指南
    搜索引擎命令大全!
    Linux入门基础篇
    CSS之BFC、IFC、FFC and GFC
    陀螺仪属性介绍和实战
    web语义化,从松散到实战
    前端跨域深入理解
    快速安装自己的Sublime系列
    hint.css使用说明
  • 原文地址:https://www.cnblogs.com/alexYuin/p/11965136.html
Copyright © 2011-2022 走看看