小编nmo*_*ses的帖子

基类中抽象方法的包装器实现

我有一个继承了许多子类的基类.我需要为抽象方法定义一个新签名,它主要是一个包装器.我试过这个

class B {
 public:
  virtual void f() = 0;
  void f(string msg) { /* print msg and call f() */ }
};

class D : public B {
 public:
  void f() override { /* implementatation */}
};

int main() {
  D d;
  d.f("msg");
}
Run Code Online (Sandbox Code Playgroud)

但它不编译并给出以下错误

error: no matching function for call to 'D::f(string)
Run Code Online (Sandbox Code Playgroud)

我的问题是:

  1. 为什么D::f(string)无法解决?
  2. 为什么以下任何一个解决了这个问题?
    • 重命名f(string)f2(string)(丑陋)
    • 定义D::f(string x) { B::f(x)}(丑陋,因为它必须在每个子类中定义)
    • 删除抽象方法,B::f()(不可接受)

更好的解决方案?

c++ inheritance abstract-class

1
推荐指数
1
解决办法
94
查看次数

标签 统计

abstract-class ×1

c++ ×1

inheritance ×1