如何真假工作运算符重载? [英] How does operator overloading of true and false work?

查看:232
本文介绍了如何真假工作运算符重载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您可以重载运营商真假我看着例子,发现这的 http://msdn.microsoft.com/en-us/library/aa691312%28v=vs.71%29.aspx



我完全不了解他们的工作。我知道,如果我写如果(OBJ)和真返回true,则如果执行。它不管是什么假的回报犯规。但是怎么做虚假工作?该文档是suggected的&放大器;&安培;运营商使用它。我写了下面的代码。我不知道怎么去和放大器;&安培;编译。 ||给我一个编译错误了。我如何获得假被称为?我如何获得和放大器;&安培;和|| ?工作



  VAR TS =新MyTimeSpan(); // TS + = TS; 
如果(TS){Console.WriteLine(为真); }
其他{Console.WriteLine(不正确); }
//Console.WriteLine(ts&放大器;&放大器; TSY:N);

类MyTimeSpan
{
公共静态MyTimeSpan运营商+(MyTimeSpan T,MyTimeSpan T2){返回新MyTimeSpan(); }
公共静态布尔运算符真(MyTimeSpan T){返回true; }
公共静态布尔运算符假(MyTimeSpan T){返回false; }
}


解决方案

该定义的属性短路操作者是它不需要如果左侧已确定的结果,以评估右侧。对于如果左边是真正,结果将是在任何情况下都能真实地必要评估右侧。对于这是相同的不同之处在于,如果左侧是,结果将是错误的。



您需要重载两个 | 真正获得 || 。和&安培; 获得&放大器;&安培;



A || b 对应像 op_true(一)? (A | b)。所以,如果真正的运算符返回true并不需要评估b的表达



A和和b 对应像 op_false(一):(A和b)。创建自定义布尔类型时,例如可为空的,所以如果假运算符返回true它并不需要评估b的表达



重载短路运营商是有用布尔变量(请参阅的DBBool


You can overload operator true and false i looked at examples and found this http://msdn.microsoft.com/en-us/library/aa691312%28v=vs.71%29.aspx

I completely dont understand how they work. I know if i write if(obj) and true returns true then the if is executed. It doesnt matter what false returns. However how does false work? in that doc it is suggected that the && operator uses it. I wrote the code below. I dont know how to get && to compile. || gives me a compile error too. How do i get false to be called? and how do i get the && and || to work?

        var ts= new MyTimeSpan();// ts += ts;
        if (ts){ Console.WriteLine("Is true"); }
        else { Console.WriteLine("not true"); }
        //Console.WriteLine(ts && ts ? "Y" : "N");

    class MyTimeSpan
    {
        public static MyTimeSpan operator +(MyTimeSpan t, MyTimeSpan t2) { return new MyTimeSpan(); }
        public static bool operator true(MyTimeSpan t) { return true; }
        public static bool operator false(MyTimeSpan t) { return false; }
    }

解决方案

The defining property of a short circuiting operator is that it doesn't need to evaluate the right side if the left side already determines the result. For or if the left side is true the result will be true in any case and it's unnecessary to evaluate the right side. For and it's the same except that if the left side is false the result will be false.

You need to overload both | and true to get ||. And & and false to get &&.

a||b corresponds to something like op_true(a)?a:(a|b). So if the true operator returns true it does not need to evaluate the expression of b.

a&&b corresponds to something like op_false(a)?a:(a&b). So if the false operator returns true it does not need to evaluate the expression of b.

Overloading the short circuiting operators is useful when creating a custom boolean type, such as nullable bools(See DBBool)

这篇关于如何真假工作运算符重载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆