Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/131.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 三值比较运算符重载_C++_Operator Overloading - Fatal编程技术网

C++ 三值比较运算符重载

C++ 三值比较运算符重载,c++,operator-overloading,C++,Operator Overloading,例如,如何实现三元比较运算符来确定a

例如,如何实现三元比较运算符来确定
a
的布尔值?

解决方案: 编码比较时,将返回类型设置为
comparison
对象,该对象可以链接其他比较,但可以隐式转换为
bool
。这甚至可以(某种程度上)处理没有按照此目的编码的类型,只需手动将它们转换为
比较类型

实施:

template<class T>
class comparison {
  const bool result;
  const T& last;
public:
  comparison(const T& l, bool r=true) :result(r), last(l) {}
  operator bool() const {return result;}
  comparison operator<(const T& rhs) const {return comparison(rhs, (result && last<rhs));}
  comparison operator<=(const T& rhs) const {return comparison(rhs, (result && last<=rhs));}
  comparison operator>(const T& rhs) const {return comparison(rhs, (result && last>rhs));}
  comparison operator>=(const T& rhs) const {return comparison(rhs, (result && last>=rhs));}
};

注意:这是由创建的,在

上可以找到一个编译过的更健壮的示例。为什么需要运算符

inline bool RangeCheck(int a, int b, int c)
{
  return a < b && b < c;
}
内联布尔范围检查(int a、int b、int c)
{
返回a
或:

定义范围检查(a,b,c)((a)<(b))&((b)<(c)))
范围(A,C)的东西更可读。包含(b)< /代码>。@ ILJJARN是的,但是这是在休息室里张贴的,我请求允许在主页上张贴。@德瑞斯:所以他的问题的答案是肯定的,但你已经得到了许可:DDon不能这样做。这是完全不符合逻辑的,因此会让阅读你的代码的人感到困惑。运算符重载的经验法则是:始终按照原语的方式执行。既然您已经回答了“可以完成吗?”,“应该完成吗?”留给读者作为练习。该函数不适用于更复杂的比较,例如
ac>d#define
的使用都被认为是有害的)@msw这就是为什么我把内联函数放在第一位:)@RadekSlupik:True它不适用于这样的表达式,但另一方面,这个表达式是不明确的。这一点从一开始就没有什么意义。
1
0
0
0
inline bool RangeCheck(int a, int b, int c)
{
  return a < b && b < c;
}
#define RANGE_CHECK(a, b, c) (((a) < (b)) && ((b) < (c)))