Classes (does this make sense?)
Ary Borenszweig
ary at esperanto.org.ar
Sat May 31 09:25:53 PDT 2008
Saaa escribió:
> Let me ask some more specific questions ..
>
> in the previous thread people suggested using the following:
>
> static this()
> {
> APPLE = new class() IFruit {
> void eat() {
> writefln("Eat APPLE");
> }
> };
>
> PEAR = new class() IFruit {
> void eat() {
> writefln("Eat PEAR");
> }
> };
> }
>
> Why the 'new class()' ? Couldn't you just create a class apple : IFruit ?
> Those fruits are in reality quite big, with multiple functions/local
> variables.
Yes. In fact, I would recommend to do that and not use the anonymous
approach, specially if the classes are big. They probably showed it like
that for brevity purposes.
> I've tried placing the APPLE in another module:
> -----------------------------
> module apple;
>
> import std.stdio;
> import main;
>
> class APPLE : IFruit {
> void eat() {
> writefln("Eat APPLE");
> }
> }
> ------------------------------
> module main;
>
> import std.stdio;
> import apple;
>
> interface IFruit
> {
> void eat();
> }
>
> IFruit APPLE;
Here you declare a variable of type IFruit called APPLE.
> IFruit PEAR;
> IFruit PLUM;
>
> static this()
> {
> PEAR = new class() IFruit {
> void eat() {
> writefln("Eat PEAR");
> }
> };
>
> PLUM = new class() IFruit {
> void eat() {
> writefln("Eat PLUM");
> }
> };
But you never initialize it, so it's null. That's why you get access
violation error.
> }
>
> int main(string[] args) {
>
> IFruit[] fruits = [APPLE, PEAR, APPLE, APPLE, PEAR, PLUM];
>
> writefln("Fruits");
> foreach( f; fruits) {
> f.eat();
> }
>
> return 0;
> }
> ---------------------------------
>
> Fruits
> Error: Access Violation
>
> :)
>
>
More information about the Digitalmars-d-learn
mailing list