为什么我不能覆盖继承的函数? [英] Why can't I override inherited function?

查看:112
本文介绍了为什么我不能覆盖继承的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我试图编译下一个建设我得到的错误:不能将参数1从'std :: vector< _Ty>'转换为'float'
为什么剂量会发生?

When I tried to compile next construction I have got the error: cannot convert parameter 1 from 'std::vector<_Ty>' to 'float' Why dose it happen?

class A
{
public:
    virtual int action(float)
    {return 5;}

    virtual int action(std::vector<float>)
    {return 10;}
};

class B : public A
{
public:
    int action(float) override
    {return 6;}
};

class C : public B
{
public:
    int action(std::vector<float>) override
    {
       B::action(std::vector<float>());
       return 7;
    }
};

int main()
{
   C instance;
   int temp = instance.action(std::vector<float>());
   getchar();
   return 0;
}


推荐答案

调用

B::action(std::vector<float>());

它需要两个步骤来决定需要进行哪个函数调用。在第一步中,它查找名称 action 。如果查找导致一个或多个函数,它停止查找。它不查找基类中的重载函数。如果查找产生多个函数名,它会尝试重载解析。

It needs two steps to decide which function call needs to be made. In the first step it looks up the name action. If the lookup results in one or more functions, it stops the lookup. It does not lookup the overloaded functions in base classes. If the lookup results in multiple function names, it tries overload resolution.

在你的情况下,查找结果只有一个函数 - int B: :action(float)。查找停止在那里。但是,该函数与所使用的参数不匹配。因此,编译器报告它是一个错误。

In your case, the lookup results in only one function - int B::action(float). The lookup stops there. However, that function does not match the argument being used. Hence, the compiler reports it as an error.

我可以想到以下方法来解决这个问题。

I can think of the following ways to resolve the problem.

使所有重载 A :: action 可用于查找 B p>

Make all overloads of A::action available for lookup in B

class B : public A
{
   public:
      using A::action;
      int action(float) override
      {return 6;}
};

更改调用,使其使用 A :: action )

class C : public B
{
   public:
      int action(std::vector<float>) override
      {
         A::action(std::vector<float>());
         return 7;
      }
};

我强烈建议使用第一种方法。

I strongly recommend using the first approach.

这篇关于为什么我不能覆盖继承的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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