【问题标题】:Problem with overriding a method (using generic types)覆盖方法的问题(使用泛型)
【发布时间】:2020-04-29 08:25:44
【问题描述】:

尝试覆盖“Solver::solve(P key)”函数时,我不断收到此错误:

标记为“覆盖”的非虚拟成员函数隐藏了虚拟成员函数。 隐藏的重载虚函数 'Solver,std::allocator>>>>::solve' 在这里声明:类型 mimsatch...

求解器.h:

...
template<class P, class S>
class Solver{
 public:
  virtual S solve(P key) = 0;
};

B.h

using namespace std;

namespace server_side {
class B: public Solver<string, vector<vector<double>>> {
 public:
  string solve(vector<vector<double>> mat) override {//<--- The error is here, on "override"
    code...
  }

但是,如果我将 vector&lt;vector&lt;double&gt;&gt;&gt; 替换为 std::string,它会完美运行。 问题是我需要它是vector&lt;vector&lt;double&gt;&gt;&gt;...

可行的替代代码:

...
using namespace std;

namespace server_side {
class B: public Solver<string, string> {
 public:
  string solve(string mat) override {
    code...
  }

任何想法如何解决它? 谢谢!

【问题讨论】:

    标签: c++ generics inheritance overriding


    【解决方案1】:

    你继承自Solver&lt;string, vector&lt;vector&lt;double&gt;&gt;&gt;PstringSvector&lt;vector&lt;double&gt;&gt;,纯虚函数有如下签名

    virtual vector<vector<double>> solve(string) = 0;
    

    你试图用

    覆盖它
    string solve(vector<vector<double>>);
    

    你需要交换一些东西。

    Solver&lt;string, string&gt; 有效,因为PS 相同,所以顺序无关紧要。


    还请注意,对于大型矩阵,按值取 vector&lt;vector&lt;double&gt;&gt; mat 效率非常低。除非您真的需要一份副本,否则您可能希望通过 const vector&lt;vector&lt;double&gt;&gt;&amp; 获取。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-04
      相关资源
      最近更新 更多