
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
120
|
Chapter 3: Classes and Structures
3.8 Indirectly Overloading the &&, ||, and ?:
Operators
Problem
You need to control the handling of the &&, ||, and ?: operators within your data
type; unfortunately, these operators cannot be directly overloaded.
Solution
Overload these operators indirectly by overloading the &, |, true, and false opera-
tors, as shown in Example 3-10.
Example 3-10. Overloading &, |, true, and false
public class ObjState
{
public ObjState(int state)
{
this.state = state;
}
public int state = 0;
public static ObjState operator &(ObjState obj1, ObjState obj2)
{
if (obj1.state >= 0 && obj2.state >= 0)
return (new ObjState(1));
else
return (new ObjState(-1));
}
public static ObjState operator |(ObjState obj1, ObjState obj2)
{
if (obj1.state < 0 && obj2.state < 0)
return (new ObjState(-1));
else
return (new ObjState(1));
}
public static bool operator true(ObjState obj)
{
if (obj.state >= 0)
return (true);
else
return (false);
}
public static bool operator false(ObjState obj)
{
if (obj.state < 0)