C++ class內的 < 和 > 重載,大於號,小於號,重載示例。


#include <iostream>

// overloading "operator = " outside class
// < 和 > 是二元操作符

//////////////////////////////////////////////////////////

class Rectangle
{
public:
	Rectangle(int w, int h) 
		: width(w), height(h)
	{};

	~Rectangle() {};


	bool operator< (Rectangle& rec);//注意比較的順序。this是被比的對象。
	bool operator> (Rectangle& rec);



public:
	int width;
	int height;
};


bool
Rectangle::operator< (Rectangle & rec)//相同的class對象互為友元,所以可以訪問private對象。< 是二元操作符,class內隱藏了this
{
	return this->height * this->width < rec.height * rec.width;
}

bool
Rectangle::operator> (Rectangle & rec)//二元操作符,class內隱藏了this
{
	return !(*this < rec);
}

//////////////////////////////////////////////////////////

int main()
{
	Rectangle a(40, 10);
	Rectangle b(40, 56);

	std::cout << (a < b) << std::endl;
	std::cout << (a > b) << std::endl;

	return 0;
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM