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

      

  • 相关阅读:
    对C# .Net4.5异步机制测试
    权限系统设计
    C#基础知识
    eclipse+pyDev
    Ubuntu下使用sublime text进行py开发
    110_02 补充模块:BeatifulSoup模块
    034 如何判断一个对象是否是可调用对象
    037 简单计算器实现
    036 re模块的小练习
    035 用Python实现的二分查找算法(基于递归函数)
  • 原文地址:https://www.cnblogs.com/alexYuin/p/11965172.html
Copyright © 2011-2022 走看看