强制所有类在多级继承层次结构中实现/覆盖“纯虚拟”方法 [英] Force all classes to implement / override a 'pure virtual' method in multi-level inheritance hierarchy

查看:157
本文介绍了强制所有类在多级继承层次结构中实现/覆盖“纯虚拟”方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中为什么 pure virtual 方法强制强制重写 ),但不是给大孩子等等。

In C++ why the pure virtual method mandates its compulsory overriding only to its immediate children (for object creation), but not to the grand children and so on ?

struct B {
  virtual void foo () = 0;
};
struct D : B {
  virtual void foo () { ... };
};

struct DD : D {
  // ok! ... if 'B::foo' is not overridden; it will use 'D::foo' implicitly
};

我没有看到任何大的事情离开这个功能。

例如,在语言设计的角度来看,可能允许 struct DD 使用 D :: foo 仅当它有一些明确的语句,如 using D :: foo; 。否则它必须重写 foo 强制。

I don't see any big deal in leaving this feature out.
For example, at language design point of view, it could have been possible that, struct DD is allowed to use D::foo only if it has some explicit statement like using D::foo;. Otherwise it has to override foo compulsory.

在C ++中有没有这种效果的实际方法? p>

Is there any practical way of having this effect in C++?

推荐答案

我发现了一个机制,至少我们被提示显式地公布重写的方法。

I found one mechanism, where at least we are prompted to announce the overridden method explicitly. It's not the perfect way, but at least somewhat near.

假设我们在 c>方法中有一些纯粹的 code> class B (base):

Suppose, we have few pure virtual methods in class B (base):

class B {
  virtual void foo () = 0;
  virtual void bar (int) = 0;
};



<被整个层次覆盖,则抽象 foo() 1为了简单起见:

class Register_foo {
  template<typename T>  // this matches the signature of 'foo'
  Register_foo (void (T::*)()) {}
};
class Base : public virtual Register_foo {  // <---- virtual inheritance
  virtual void bar (int) = 0;
  Base () : Register_foo(&Base::foo) {}  // <--- explicitly pass the function name
};

层次结构中的每个后续子类都必须注册< c $ c> foo 在其每个构造函数 显式内。例如:

Every subsequent child class in the hierarchy would have to register its foo inside its every constructor explicitly. e.g.:

struct D : B {
  D () : Register_foo(&D::foo) {}
  D (const D &other) : Register_foo(&D::foo) {}
  virtual void foo () {};
};

这个注册机制与业务逻辑无关。但是至少在任何子类的构造函数中,它会提到, foo 它正在使用。

虽然, class 可以选择使用自己的 foo 或其父级的 foo 注册,最少是明确宣布的

This registration mechanism has nothing to do with the business logic. But at least inside the constructor of any child class it would be mentioned that, which foo it's using.
Though, the child class can choose to register using its own foo or its parent's foo, but at least that is announced explicitly.

这篇关于强制所有类在多级继承层次结构中实现/覆盖“纯虚拟”方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆