1

如何将一个类传递给另一个类方法?使用这个例子,“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);
    }
}
4

1 回答 1

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
{

}
于 2013-11-07T21:33:21.640 回答