nmo*_*ses 1 c++ inheritance abstract-class
我有一个继承了许多子类的基类.我需要为抽象方法定义一个新签名,它主要是一个包装器.我试过这个
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)
我的问题是:
D::f(string)无法解决?f(string)为f2(string)(丑陋)D::f(string x) { B::f(x)}(丑陋,因为它必须在每个子类中定义)B::f()(不可接受)更好的解决方案?
问题是你藏 B::f(std::string)在这里:
class D : public B {
public:
void f() override;
};
Run Code Online (Sandbox Code Playgroud)
当你打电话D.f("msg"),名称查找会发现一个f()在D望而止步.我们首先发现候选函数然后执行重载决策.由于那个碰巧没有参数,你得到编译错误.
如果你想使用其他重载f,你需要将它带入D,如下所示:
class D : public B {
public:
using B::f;
void f() override;
};
Run Code Online (Sandbox Code Playgroud)
现在我们有D::f()(被覆盖的虚函数)和D::f(std::string )(我们从中引入B).
另一个简单的解决方案是简单地重命名一个或另一个函数,这样你就不会有这个问题.