【问题标题】:error: out-of-line definition of 'test' does not match any declaration in 'B<dim>'错误:“test”的离线定义与“B<dim>”中的任何声明都不匹配
【发布时间】:2014-04-30 01:18:24
【问题描述】:

我有一个小问题正在杀死我!我不知道下面的代码似乎有什么问题。我应该能够实现从超类继承的功能,不是吗?但我得到error: out-of-line definition of 'test' does not match any declaration in 'B&lt;dim&gt;'

template <int dim>
class A 
{
public:
  virtual double test() const ;
};

template <int dim>
class B : public A <dim>
{
};

template <int dim>
double B<dim>::test () const
{
  return 0;
}

我在 Mac 上使用 clang(Apple LLVM 版本 5.1)。

【问题讨论】:

    标签: c++ macos templates inheritance virtual


    【解决方案1】:

    试试

    template <int dim>
    class B : public A <dim>
    {
    public:
         virtual double test () const;
    };
    
    // Function definition
    template <int dim>
    double B<dim>::test () const
    {
      return 0;
    }
    

    您仍然需要定义声明类声明的函数。

    【讨论】:

    • 但是重新声明函数不是违背了继承的目的吗?我想要一个超类来定义许多子类声明的所有必要功能。我不想再重复声明了!另外,您的修复程序不会隐藏 A::test 功能吗?
    • @FahadAlrashed 不!如果您不重新声明它,编译器应该如何知道类B 提供它自己的实现。 '我不想再重复声明了!'要编写有效的 c++ 代码,你必须这样做!
    • 谢谢。我仍然认为 C++ 应该足够聪明,知道函数正在被覆盖。
    • @FahadAlrashed 我已经编辑了答案。 C++ 确实有这个特性来明确指定你想要override。回答者可能忘记了。
    • @FahadAlrashed :B 的构造函数需要知道函数被覆盖,以便相应地设置 vtable。但是,该构造函数和 test() 定义可能在不同的编译单元中。
    【解决方案2】:

    问题是你试图在B类的类定义之外定义函数test。你必须首先在类中声明它

    template <int dim>
    class B : public A <dim>
    {
       double test() const;
    };
    

    【讨论】:

    • 再次......重新声明函数不会破坏继承的目的吗?我不明白为什么我需要重新声明一个继承的函数。
    • @Fahad Alrashed 您正在尝试定义未在此类中声明的 B 类函数。如果你想重新定义一个虚函数,你需要在这个类中声明它。
    • 如果一个人可以在一个类之外声明/定义一个函数的方法来覆盖一个基本的实现,谁能说它不能在其他文件中完全定义/声明呢?这将是一团糟,因为它允许在任何地方任意覆盖方法并导致无法维护的污泥。
    猜你喜欢
    • 1970-01-01
    • 2015-08-28
    • 2011-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-10
    • 1970-01-01
    相关资源
    最近更新 更多