继承的成员函数的重载 [英] Overloads of inherited member functions

查看:145
本文介绍了继承的成员函数的重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以在公共继承接口中存在的类重载方法吗?
这似乎是明确和有用的,但编译器(VC,英特尔,GCC)都抱怨,至少通过我的建设。
下面是一个玩具示例。继承的rebound()函数有两个清除重载,但这不会编译。如果您重命名任何类中的rebound()方法,它都可以正常工作,但如果他们共享相同的成员函数名称(即使它们使用不同的参数类型重载),您会遇到致命错误函数调用的参数太少。

Can a class overload methods that also exist in the publicly inherited interface? It seems like this is unambiguous and useful, but compilers (VC, Intel, GCC) all complain, at least by my construction. Below is a toy example. The inherited rebound() function has two clear overloads, yet this will not compile. If you rename the rebound() method in either class, it works fine, but if they share the same member function name (even though they're overloaded with different argument types!) you get a fatal error of "too few arguments to function call."

解决方法很简单(我只是重命名方法),但我只是想了解这是否C ++限制(以及为什么会这样)。

The workaround is trivial (I'll just rename the methods) but I'm just trying to understand if this is a C++ restriction (and why it would be).


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


推荐答案

使用节点中添加 c>声明:

Add a using in the Node declaration:

using Bound::rebound;
void rebound() { rebound(left, right); }



2。显式引用基类方法



使用Bound命名空间:

2. Explicitly refer to the base class method

Use the Bound namespace:

void rebound() { Bound::rebound(left, right); }



3。定义/重新定义派生类中的所有重载



将实现委派给基类(如果这是在头中完成的,不应该有任何惩罚,因为内联):

3. Define/redefine all overloads in the derived class

Delegate the implementation to the base class (if this is done in the header, there shouldn't be any penalty thanks to inlining):

void rebound(const Bound *a, const Bound *b) { Bound::rebound(a, b); };
void rebound() { rebound(left, right); }

更多信息:
https://isocpp.org/wiki/faq/strange-inheritance#overload-derived

这篇关于继承的成员函数的重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆