gpt4 book ai didi

c++ - 在 c++ 中有关系的接口(interface)有很好的替代吗

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:34:30 24 4
gpt4 key购买 nike

我在 GUI 设计中面临 OOP 问题,但让我用动物示例来说明它。让我们进行以下设置:

  • 有一个基类Animal
  • 任何派生类都可以has-a dentry
  • 所有有 dentry 的动物都能咬人() <=> 没有 dentry 的动物不能咬人()
  • 每个动物 Bite() 都以相同的方式(在 Teeth 类中有默认实现)

对于动物来说,有一个 dentry 是很自然的,但现在我需要一些类似有一个关系的界面。例如,如果我有一个动物 vector ,如果它们可以的话,我该如何制作每个 Bite()?

std::vector<Animal *> animals;
animals.push_back(new dog());
animals.push_back(new fly());
animals.push_back(new cat());

void Unleash_the_hounds(std::vector<Animal *> animals)
{
//bite if you can!
}

我想出了几个解决方案,但似乎没有一个是完全合适的:

1.) 每个带有 Teeth 的类也实现接口(interface) IBiting。然而,这个解决方案引入了很多代码重复,我需要在每个类中“实现”Bite():

class Cat : public Animal, public IBiting {
Teeth teeth;
public:
virtual void Bite() { teeth.Bite(); }
}

2.) 给每只动物 dentry ,但只允许一些动物使用它们。 注意:语法可能是错误的——这只是说明

class Animal{
static cosnt bool canBite = false;
Teeth teeth;
public:
void Bite() { this->canBite ? teeth.Bite() : return; }
}

class Cat {
static cosnt bool canBite = true;
}

3.) 更多继承 - 创建类 BitingAnimal 并派生它。好吧,这可行,但如果我需要派生(非)飞行动物怎么办,其中一些有 dentry 。

class Animal{}
class BitingAnimal : public Animal {
Teeth teeth;
}

并用作 BitingAnimal.teeth.Bite()

4.) 多重继承。这通常是不鼓励的,并且在大多数语言中是不可能的,而且 Cat 是 Teeth 也是不合逻辑的。

class Cat : public Animal, public Teeth {
}

5.) 可以咬人的类的枚举 - 听起来很奇怪。


还是我只是把它弄得太复杂而错过了一些重要的东西?

最佳答案

您没有提到的另一种方法是只为 dentry 提供抽象,但在基类中实现咬合。这减少了重复,因为派生类只需要指定如何访问 dentry 而不是如何咬合。通过返回一个指向 dentry 的指针,我们可以允许一个空指针来指示该动物没有 dentry 。这是一个例子:

#include <vector>

struct Teeth {
void bite() { }
};

struct Animal {
virtual Teeth *teethPtr() = 0;

void biteIfYouCan() { if (teethPtr()) teethPtr()->bite(); }
};

struct Dog : Animal {
Teeth teeth;
Teeth *teethPtr() override { return &teeth; }
};

struct Fish : Animal {
Teeth *teethPtr() override { return nullptr; }
};

int main()
{
Dog dog;
Fish fish;

std::vector<Animal *> animals {&dog,&fish};

for (auto animal_ptr : animals) {
animal_ptr->biteIfYouCan();
}
}

关于c++ - 在 c++ 中有关系的接口(interface)有很好的替代吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25343088/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com