在C ++中覆盖Base的重载函数 [英] Overriding a Base's Overloaded Function in C++

查看:97
本文介绍了在C ++中覆盖Base的重载函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

C ++重载解析

我碰到一个问题,函数的基类,所有的重载版本的函数,然后隐藏。这是设计还是我只是做错了?

I ran into a problem where after my class overrode a function of its base class, all of the overloaded versions of the functions were then hidden. Is this by design or am I just doing something wrong?

例如。

class foo
{
  public:
    foo(void);
    ~foo(void);
    virtual void a(int);
    virtual void a(double);
};

class bar : public foo 
{
  public:
    bar(void);
    ~bar(void);
    void a(int);
};

下面将会给出一个编译错误,说bar里没有一个/ p>

the following would then give a compile error saying there is no a(double) function in bar.

main() 
{
  double i = 0.0;
  bar b;
  b.a(i);
}


推荐答案

/ p>

In class bar, add

using foo::a;

这是C ++中常见的getcha。一旦在类范围中找到名称匹配,它就不会在继承树的上面看到重载。通过指定'using'声明,将'a'的所有重载从'foo'带到'bar'的范围。

This is a common 'gotcha' in C++. Once a name match is found in the a class scope, it doesn't look further up the inheritance tree for overloads. By specifying the 'using' declaration, you bring all of the overloads of 'a' from 'foo' into the scope of 'bar'. Then overloading works properly.

请记住,如果现有的代码使用'foo'类,其含义可能会被额外的重载更改。或者额外的重载可能引入歧义,并且代码将无法编译。这在詹姆斯·霍普金的回答中指出。

Keep in mind that if there is existing code using the 'foo' class, its meaning could be changed by the additional overloads. Or the additional overloads could introduce ambiguity and and the code will fail to compile. This is pointed out in James Hopkin's answer.

这篇关于在C ++中覆盖Base的重载函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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