加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 强制所有类在多级继承层次结构中实现/覆盖“纯虚拟”方法

发布时间:2020-12-16 10:31:06 所属栏目:百科 来源:网络整理
导读:在C中为什么纯虚方法强制要求它的直接子项(用于创建对象),而不是给大孩子等等? 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' imp
在C中为什么纯虚方法强制要求它的直接子项(用于创建对象),而不是给大孩子等等?

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
};

离开这个功能我没有看到什么大不了的.
例如,在语言设计的角度来看,结果DD只有在它有一些像D :: foo;这样的显式语句时才允许使用D :: foo.否则它必须覆盖foo强制.

在C中有这种效果的实用方法吗?

解决方法

我发现了一种机制,至少我们会被提示明确宣布重写方法.这不是完美的方式,但至少有点接近.

假设,我们在B类(基础)中几乎没有纯虚方法:

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

其中,我希望foo()被整个层次结构覆盖,然后抽象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
};

层次结构中的每个后续子类都必须在其每个构造函数中明确注册其foo.例如.:

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

此注册机制与业务逻辑无关.但至少在任何子类的构造函数中,都会提到它,它正在使用它.虽然,子类可以选择使用自己的foo或其父类的foo进行注册,但至少会明确公布.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读