zoukankan      html  css  js  c++  java
  • C++ class内的=重载,拷贝赋值函数copy op=,重载示例。必须是class内

    #include <iostream>
    
    // overloading "operator = " inside class
    // = 是一元操作符。不写,编译器会提供 默认 拷贝赋值函数。可以通过显式“=delete”来禁用默认。对于复杂class的默认=可能会造成问题,请特别注意。
    
    //////////////////////////////////////////////////////////
    
    class Rectangle
    {
    public:
    	Rectangle(int w, int h) 
    		: width(w), height(h)
    	{};
    
    	~Rectangle() {};
    
    	bool operator== (Rectangle& rec);
    
    	Rectangle& operator= (Rectangle& rec);
    
    
    public:
    	int width;
    	int height;
    };
    
    //////////////////////////////////////////////////////////
    bool 
    Rectangle::operator==(Rectangle & rec)//相同的class对象互为友元,所以可以访问private对象。== 是二元操作符,class内隐藏了this
    {
    	return this->height == rec.height
    		&& this->width == rec.width;
    }
    
    Rectangle&
    Rectangle::operator=(Rectangle & rec)
    {
    	// 一定要在 = 中进行自我复制检查!所以要先定义 == 方法。
    	// 避免不必要的开销,以及避免影响正在使用既有的变量的某些函数。
    
    	if (*this == rec)
    		return *this;
    
    	this->height = rec.height;
    	this->width = rec.width;
    
    	return *this;
    
    }
    
    //////////////////////////////////////////////////////////
    
    int main()
    {
    	Rectangle a(40, 10);
    	Rectangle b = a;
    
    	std::cout << (a == b) << std::endl;
    
    	return 0;
    }
    

      

  • 相关阅读:
    各种机器学习方法概念
    深入理解拉格朗日乘子法(Lagrange Multiplier) 和KKT条件
    肤色识别
    创建自己的窗口消息
    模糊C均值
    Fisher线性判别
    用遗传算法加强足球游戏的人工智能
    人工智能-遗传算法解决推箱子问题现实
    LBP特征
    VC 制作系统托盘程序实现将窗口最小化到系统托
  • 原文地址:https://www.cnblogs.com/alexYuin/p/11965172.html
Copyright © 2011-2022 走看看