www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Strange enum

reply orgoton <orgoton mindless.com> writes:
I have this in a class:

enum ActorType:ubyte
{Unit=0, Building=1, Other=2
}

then,
class Actor
{
this()
{
assert(this.getType()<5); //THIS FAILS
}
(...)
public final ActorType type=ActorType.Other;
protected ubyte getType()
{
return cast(ubyte)type;
}

}

In a static constructor, an Actor is created to test another class, and the
program ends in an assert error.
Apr 11 2007
parent =?ISO-8859-1?Q?R=e9my_Mou=ebza?= <ray.jay.ay.moueza gmail.com> writes:
orgoton Wrote:

 I have this in a class:
 
 enum ActorType:ubyte
 {Unit=0, Building=1, Other=2
 }
 
 then,
 class Actor
 {
 this()
 {
 assert(this.getType()<5); //THIS FAILS
 }
 (...)
 public final ActorType type=ActorType.Other;
 protected ubyte getType()
 {
 return cast(ubyte)type;
 }
 
 }
 
 In a static constructor, an Actor is created to test another class, and the
program ends in an assert error.

In Java, one declare constants with final. In D we use the const keyword. Note that this has nothing to do with C++ const type qualifier. There is a certainly a bunch of code in your program that assign a new value to your Actor.type variable. Using const, you'll get a compile time error. final is use to explicitly ask the D compiler to make a non polymorphic method (C++ virtual function): by default the D compiler calculate what should be polymorphic or not and optimises in consequences. I hope this information helps, import std.stdio ; class ConsoleOutput { this () {} ConsoleOutput opShl (T) ( T something ) { writef ( something ); return this ; } } ConsoleOutput cout ; static this () { cout = new ConsoleOutput ; } enum ActorType : ubyte { Unit = 0, Building = 1, Other = 2 } class Actor { this () { cout << "constructor " << \n ; cout << this.getType () << \n ; this.type = cast ( ActorType ) 10 ; // without const Ok, with const: compile time error. assert ( this.getType () < 5, "problem" ); //THIS FAILS } //public final ActorType type = ActorType.Other ; public const ActorType type = ActorType.Other ; protected ubyte getType() { cout << "getType ()" \n ; return cast(ubyte)type; } } void main () { cout << "main" \n ; auto actor = new Actor ; }
Apr 11 2007