【发布时间】:2013-12-09 15:51:06
【问题描述】:
我试图了解 Haskell 中的面向对象风格编程,因为我知道由于缺乏可变性,事情会有些不同。我玩过类型类,但我对它们的理解仅限于它们作为接口。所以我编写了一个 C++ 示例,它是具有纯基和虚拟继承的标准菱形。 Bat 继承 Flying 和 Mammal,Flying 和 Mammal 都继承 Animal。
#include <iostream>
class Animal
{
public:
virtual std::string transport() const = 0;
virtual std::string type() const = 0;
std::string describe() const;
};
std::string Animal::describe() const
{ return "I am a " + this->transport() + " " + this->type(); }
class Flying : virtual public Animal
{
public:
virtual std::string transport() const;
};
std::string Flying::transport() const { return "Flying"; }
class Mammal : virtual public Animal
{
public:
virtual std::string type() const;
};
std::string Mammal::type() const { return "Mammal"; }
class Bat : public Flying, public Mammal {};
int main() {
Bat b;
std::cout << b.describe() << std::endl;
return 0;
}
基本上,我对如何将这样的结构转换为 Haskell 感兴趣,基本上这将允许我拥有一个 Animals 列表,就像我可以拥有一个指向 Animals 的(智能)指针数组C++。
【问题讨论】:
-
您熟悉类型类吗? en.wikipedia.org/wiki/Type_class
-
正如问题所说,是的,但是我不确定如何将它们用作层次结构中的部分实现类(而不是基本上 Java 接口)。我认为示例代码是最快的学习方式。
-
@Clinton 你的用例是什么?我认为当你开始尝试像面向对象一样编写 Haskell 代码时会遇到问题。
-
@bheklilr:这只是学习 C++ 概念如何(或不)转换为 Haskell 的示例。
-
该示例需要一个真实世界的上下文,其中 OOP 是有意义的,以便正确翻译成 Haskell。编写一个简单的程序,其中 OOP 结构很重要。
标签: c++ oop haskell functional-programming virtual-functions