A demo program on class and stuct, Am I right?

solotony at sohu.com solotony at sohu.com
Sat Jun 17 19:36:55 PDT 2006



class TheObject
{
int a;

bool opEquals(TheObject b)
{
return true;
}
}

struct TheValue
{
int a;
}

void demoObj()
{
TheObject a, b; //both are ref;

assert(a is null);  //used be null

//if( a == b){     //runtime crash here, == is a call to opEqual method.
//}

a = new TheObject; //heap object, gc equipped.
b = new TheObject;

assert (a !is b); //ref to differet object
assert (a == b);  //the object is equal.

auto TheObject stackObject = new TheObject; // the only way to create a stack
object.


TheObject* p;

assert(p is null);

//p = a; //cannot implicitly convert ref to pointer;
p = &a; // ok
p.a = 4;
assert( a.a == 4); //access successfully

//b = p; //convert p to ref is illegeal;
b = *p; //ok

assert(a is b);  //ok, ref to same object.

TheObject* q;
q = &b;

//can we call opEquals method through pointer?
assert(*p == *q);

//and identic? why? see /d/expression.html#EqualExpression
assert(*p is *q);

q = &a;
//the pointer value? 
assert(p == q);

//and what's the identical comparing mean? /d/expression.html#EqualExpression
assert(p is q);
}

void demoValue()
{
TheValue v; //on stack?
v.a = 4;    //yes, on stack;

//v = new TheValue; //no, v is a value, new TheValue is a pointer(ref?)
v = *new TheValue;  //ok. temporary copy and assign?

//auto TheValue v1 = new TheValue; //can't be auto value.
TheValue v1 = v;

assert( v1 == v);  //call to opEquals
assert( v1 is v);  //why this ? see /d/expression.html#EqualExpression

TheValue *p;
p = new TheValue; //on heep and gc?

assert(*p == v); 

//no different between obj ptr and value ptr ?

}


int main()
{
demoObj();
demoValue();
return 0;
}





More information about the Digitalmars-d-learn mailing list