如何在 C++ 中编写一个 interface/supertypes 的程序?

How does one program to an interface/supertypes in C++?

我正在阅读 Head First Design Patterns 这本书,并且我也在尝试学习 C++。 在书中它说编程到 interface/supertype 而不是编程到实现,作者给出了这个 java 示例:

//programming to implementation
Dog d = new Dog();
d.bark();
//programming to an interface/supertype (here Animal)
Animal animal = new Dog();
animal.makeSound();

要在 C++ 中做同样的事情,您会使用抽象 class 还是泛型编程?那到底会是什么样子?

感谢您的帮助!

免责声明:将 Java code/patterns/best 实践直接翻译成 C++ 会让您陷入痛苦的世界。

Java 有接口。在 C++ 中最接近的是抽象基 class:

struct Animal {
    virtual void makeSound() const = 0;   // <- pure virtual, ie no implementation in Animal
    virtual ~Animal() = default;
};

struct Dog : Animal {
    void bark() const { std::cout << "Moo"; }
    void makeSound() const override {  bark(); }
};


//programming to implementation
Dog d;                            // C++ has values, not everything is a reference like in Java
d.bark();
//programming to an interface/supertype (here Animal)
std::shared_ptr<Animal> animal = std::make_shared<Dog>();  // Use smart pointers, not raw ones
                                                           // and don't use new in C++
animal->makeSound();

您是否也可以使用模板来做到这一点很难/不可能回答,因为这只不过是一个示例来说明接口/抽象基础的使用class,而这是唯一的要求。

正如评论中指出的那样,模式的存在并不是为了它们本身,而是为了帮助开发。一旦解决了实际问题并且对模式有了一定的了解,您就会注意到某个问题何时需要使用模式。