How does operator overloading of true and false work?

前端 未结 3 985
清酒与你
清酒与你 2020-12-06 11:53

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 und

相关标签:
3条回答
  • 2020-12-06 12:07

    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)

    0 讨论(0)
  • 2020-12-06 12:11

    You will need to override & operator for && and | or ||.

    Somthing like this: (Just a dummy code)

    public static MyTimeSpan operator &(MyTimeSpan t, MyTimeSpan s) { return t; }
    
    public static MyTimeSpan operator |(MyTimeSpan t, MyTimeSpan s) { return t; }
    
    0 讨论(0)
  • 2020-12-06 12:19

    When overloading the true and false operators they don't just return true and false, they are used to determine if a value of your type is considered to be true or false.

    If for example a zero value in your class represents false, then a non-zero value represents true:

    public static bool operator true(MyTimeSpan t) { return t.Value != 0; }
    public static bool operator false(MyTimeSpan t) { return t.Value == 0; }
    

    As the operators are each others inverse, the compiler doesn't need to use both to determine if a value is true or false. If you write if(obj) the compiler will use the true operator to determine if the value is true.

    0 讨论(0)
提交回复
热议问题