【发布时间】:2015-07-17 02:50:30
【问题描述】:
我有一个继承了许多子类的基类。我需要为一个抽象方法定义一个新的签名,它主要是一个包装器。我试过这个
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");
}
但它没有编译并给出以下错误
error: no matching function for call to 'D::f(string)
我的问题是:
- 为什么不能解析
D::f(string)? - 为什么以下任何一项都可以解决问题?
- 将
f(string)重命名为f2(string)(丑陋) - 定义
D::f(string x) { B::f(x)}(丑陋,因为它必须在每个子类中定义) - 删除抽象方法
B::f()(不可接受)
- 将
有更好的解决方案吗?
【问题讨论】:
-
派生的
f覆盖隐藏了基础f(std::string)。尝试将using B::f;放在派生类中,以将它们从B引入 -
@Alejandro 答案属于答案,而不是 cmets。
-
鉴于一个
f调用另一个f,他们有微妙的不同角色。因此,为了清楚起见(除了解决问题),重命名它们以区分更高级别的发起者和实现可能是值得的。
标签: c++ inheritance abstract-class