为什么这个子类'父方法调用不是多态的?

时间:2015-07-15 16:55:35

标签: oop inheritance polymorphism d

我最近一直在涉及Dlang,因为在使用Python这么长时间之后,C ++并没有和我坐在一起。在涉足时,我遇到了我认为在多态中非常简单的练习。我想你最终用户可能无法理解的原因是你会期望某些东西能起作用,它实际上做的是两件完全不同的东西。话虽这么说,这是我的" sandbox.D"的源代码:

import std.stdio;

class Animal {
    string voice = "--silence--";
    void speak() {
        writeln(this.voice);
    }
}

class Dog : Animal {
    string voice = "Whoof!";
}

int main() {
    auto a = new Animal();
    auto d = new Dog();

    writeln(a.voice); // Prints "--silence--"
    writeln(d.voice); // Prints "Whoof!"

    a.speak(); // Prints "--silence--"
    d.speak(); // Prints "--silence--" NOT "Whoof!"

    return 0;
}

我想我的问题是为什么"这个"关键字似乎没有按照C ++后继语言的预期发挥作用。

1 个答案:

答案 0 :(得分:1)

另一种方法是使用模板这个参数:

import std.stdio;

class Animal {
    string voice;

    void speak(this C)() {
        writeln((cast(C)this).voice);
    }
}

class Dog : Animal {
    string voice = "Whoof!";
}

int main() {
    auto a = new Animal();
    auto d = new Dog();

    a.speak(); // Prints ""
    d.speak(); // Prints "Whoof!"

    return 0;
}

或者当你不需要成为会员的声音时:

import std.stdio;

class Animal {
    static immutable voice = "";

    void speak(this C)() {
        writeln(C.voice);
    }
}

class Dog : Animal {
    static immutable voice = "Whoof!";
}

int main() {
    auto a = new Animal();
    auto d = new Dog();

    a.speak(); // Prints ""
    d.speak(); // Prints "Whoof!"

    return 0;
}