14 c++ inheritance overloading
一个类可以重载公共继承接口中也存在的方法吗?这似乎是明确和有用的,但编译器(VC,英特尔,GCC)都抱怨,至少我的建设.以下是一个玩具示例.继承的rebound()函数有两个明确的重载,但这不会编译.如果你重命名任何一个类中的rebound()方法,它工作正常,但如果它们共享相同的成员函数名称(即使它们被不同的参数类型重载!)你会得到一个致命的错误:"函数参数太少呼叫."
解决方法是微不足道的(我只是重命名方法),但我只是想了解这是否是C++限制(以及为什么会这样).
#include
class Bound {
public:
Bound() : x0(0.0), x1(0.0) {};
Bound(double x) : x0(x), x1(x) {};
double width() const {return x1-x0;}
void rebound(const Bound *a, const Bound *b);
private:
double x0, x1;
};
void Bound::rebound(const Bound *a, const Bound *b)
{
if (a && b) {
x0=std::min(a->x0, b->x0);
x1=std::max(a->x1, b->x1);
}
}
class Node : public Bound {
public:
Node(double x) : Bound(x), left(0), right(0) {};
Node(Node *a, Node *b) : left(a), right(b) {rebound();}
void rebound() { rebound(left, right); }
private:
Node *left;
Node *right;
};
int main() {
Node A(1.0);
Node B(2.0);
Node C(&A, &B);
}
Run Code Online (Sandbox Code Playgroud)
Ate*_*ral 22
你可以做三件事:
using在Node声明中添加一个:
using Bound::rebound;
void rebound() { rebound(left, right); }
Run Code Online (Sandbox Code Playgroud)
使用Bound命名空间:
void rebound() { Bound::rebound(left, right); }
Run Code Online (Sandbox Code Playgroud)
将实现委托给基类(如果在标题中完成,则由于内联而不应该有任何惩罚):
void rebound(const Bound *a, const Bound *b) { Bound::rebound(a, b); };
void rebound() { rebound(left, right); }
Run Code Online (Sandbox Code Playgroud)
更多信息:https: //isocpp.org/wiki/faq/strange-inheritance#overload-derived