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