Compare two objects

Qian Xu quian.xu at stud.tu-ilmenau.de
Tue Feb 10 04:57:21 PST 2009


Hi All,

I want to test, if two objects are equal. 
The rules are as follows: 
1. When both are null, it should return true. 
2. When one of them is null, it should return false.
3. When both not null, then compare their values (as two strings)

My test code
---------------------------------------------------------------
class Test {
  private int value;
  this(int value) {
    this.value = value;
  }
  public int getValue() {
    return this.value;
  }
  bool opEquals(Test obj) {
    if (obj is null) {
      return this is null;
    }
    return this.getValue() == obj.getValue();
  }
}

procedure test(Test a, Test b) {
  if (a is null && b is null) return true;
  if (a !is null && a == b) return true;
  return false;
}

void main()
{
  Test a;
  Test b = new Test(100);
  assert(test(a, b)); // ok
  assert(a != b); // av error
}
----------------------------------------------------------------

If object at the left side of the != is null, I will get an AV error
immediately.
If I want to compare two objects safely, I have to write my own test(..)
function.
But this is not nice.

Can someone explain, is this a design shortcoming of D-Compiler, or I am
wrong.

Best regards
--Qian Xu





More information about the Digitalmars-d-learn mailing list