0
点赞
收藏
分享

微信扫一扫

bool operator==(const T& t) const,关系运算符重载

zhyuzh3d 2022-04-13 阅读 63
c++

基本定义:

bool operator ==( )可以分为——bool operator ==( const bool& other)、bool operator ==( const T& other), 其中T代表类型;分别表示与bool类型的比较,和与本类对象的比较

运算符函数定义的一般格式如下:

<返回类型说明符>  operator <运算符符号> (<参数表>)  { <函数体> }

关系运算符重载:

bool operator == (const T& ); 
bool operator != (const T& );
bool operator < (const T& );
bool operator <= (const T& );
bool operator > (const T& );
bool operator >= (const T& );

举例说明:

struct Connection   //定义结构体Connection
	{
		Gate* gate = nullptr;
		size_t input_idx = std::numeric_limits<size_t>::max();   //size_t是无符号int型

		bool operator==(const Connection& other) const  //关系运算符"=="重载,允许自定义类型对象进行对比操作;
		{ //类对象前加const变成常对象;括号中的const表示参数other对象不会被修改,最后的const表明调用函数对象不会被修改
			return std::tie(gate, input_idx) == std::tie(other.gate, other.input_idx);
		}

		bool operator!=(const Connection& other) const
		{
			return !operator==(other);
		}
	};
举报

相关推荐

0 条评论