首页 > 编程语言 > 详细

C++ class内的==重载,判断相等,测试等于,重载示例。二元操作符

时间:2019-12-01 11:19:29      阅读:60      评论:0      收藏:0      [点我收藏+]
#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;
}

  

C++ class内的==重载,判断相等,测试等于,重载示例。二元操作符

原文:https://www.cnblogs.com/alexYuin/p/11965136.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!