c++ - 纯虚函数和多重继承

标签 c++ multiple-inheritance pure-virtual

我有一个(保证树形的)类级联

class rock_bottom {
    ...
    virtual foo() = 0;
};

class A : rock_bottom {...}

class intermediate: rock_bottom {...}   

class B : intermediate {...}

class higher_up {...}

class C : higher_up {...}

我想在字母类 A、B、C 中实现 foo()。我需要在哪里声明 foo? (虚拟的?纯粹的?)我是否需要在中间层 intermediate 和 higher_up 中进行(简单的)实现?

最佳答案

问题:

I want to implement foo() in the lettered classes A, B, C. Where do I need to declare foo? (Virtual? Pure?)

回答:

这个问题需要反过来问。在哪个基类中创建接口(interface) foo 有意义。让我们来看看您可能会在应用程序中找到的一些类。

struct Shape {};
struct Rectangle : public Shape {};
struct Square : public Rectangle {};
struct Ellipse : public Shape {};
struct Circle : public Ellipse {};

所有 Shape 都能够返回它们的面积和周长是有道理的。因此,您将它们作为 virtual 成员函数放在 Shape 中。

struct Shape 
{
   virtual double area() const = 0;
   virtual double perimeter() const = 0;
};

在创建 Shape 子类型的实例之前,您必须实现它们。

如果您希望能够创建一个Rectangle,那么这些函数必须在Rectangle 中实现,因为没有其他中间类。

如果您希望能够创建一个Square,那么这些函数必须在RectangleSquare 或两者中实现。

同样,如果您希望能够创建一个 Ellipse,那么这些函数必须在 Ellipse 中实现,因为没有其他中间类。

如果您希望能够创建一个Circle,那么这些函数必须在EllipseCircle 或两者中实现。

但是,只有 Rectangle 有长度和宽度。只有 Ellipse 具有长半径和短半径。在 Shape 中添加虚拟成员函数以返回这些值是没有意义的。

问题:

Do I need (trivial) implementations in the middle layers intermediate and higher_up?

回答:

不,你不知道。上一个问题的答案应该更清楚地说明这一点。

关于c++ - 纯虚函数和多重继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28723470/

相关文章:

python - 为什么可以调用父类(super class)没有的方法

c++ - 虚拟继承 : Error: no unique final overrider

c++ - 多个 vtables,在打电话时以错误的方式结束

c++ - 如何实现纯虚拟析构函数?

c++ - 纯虚析构函数的目的是什么?

c++ - 奇怪的 std::list 迭代行为

c++ - 在基类上自动推断派生类上函数的返回类型

c++ - 如何在 C++ 中用 UTF-8 字符解码 URI

c++ - rabbitmq c++ 客户端未在 5672 端口连接到 rabbitmq-server

c++ - CRTP 导致段错误