D lang - 通过ref class传递给class方法

时间:2013-11-07 19:48:57

标签: d

如何将类传递给另一个类方法?使用此示例“animal.name”在eat方法中将为空。

import std.stdio;

void main()
{
    Animal cat = new Animal;
    Animal dog = new Animal;

    cat.name = "fluffy";
    dog.name = "bruce";

    dog.eat(cat);
}

class Animal
{
    auto name = "none";

    void eat( Animal animal )
    {
        writeln(this.name);
        writeln("is going to eat");
        writeln(animal.name);
    }
}

1 个答案:

答案 0 :(得分:2)

好吧,运行这个例子是有效的,所以它必须是我正在使用的实际代码的另一个问题(与我原来的问题无关)。

对于将来遇到此问题的任何人来说,这会编译并运作:

import std.stdio;

void main()
{
    Cat cat = new Cat;
    Dog dog = new Dog;

    cat.name = "fluffy";
    dog.name = "bruce";

    dog.eat(cat);
}

class Animal
{
    auto name = "none";

    void eat( Animal animal )
    {
        writeln(this.name);
        writeln("is going to eat");
        writeln(animal.name);
    }
}

class Cat: Animal
{

}

class Dog: Animal
{

}