【问题标题】:abstract method in namespace命名空间中的抽象方法
【发布时间】:2013-04-26 05:44:02
【问题描述】:

我有一个很奇怪的问题。

我有 3 个文件:
图.h:

#ifndef FIGURE_H
#define FIGURE_H
namespace figure
{
    class figure
    {
        public:
            figure(position &p,color c);
            virtual bool canMove(const position &p)=0;
            virtual bool move(const position &p)=0;
        protected:
            color col;
            position &p;
    };
    class king : public figure
    {
    };
};
#endif // FIGURE_H

国王.h:

#ifndef KING_H
#define KING_H

#include "./figure.h"
namespace figure
{
   class king : protected figure
   {
   };
}
#endif // KING_H

和 king.cpp:

#include "king.h"
bool figure::king::canMove(const position &p)
{
}

我正在编译它: gcc -std=c11 -pedantic -Wall -Wextra

但问题是我收到了这个错误:

/src/figure/figure.h:24:45: 错误: no ‘bool figure::king::canMove(const position&)' 声明的成员函数 类‘figure::king’

我该怎么办? 非常感谢!

【问题讨论】:

  • 命名空间和函数体后面不需要分号。
  • @chris - 将其发布为答案
  • @ZacharyKniebel,我非常怀疑这会导致错误。

标签: c++


【解决方案1】:

您需要在class king声明该函数。

class king : public figure
{
  virtual bool canMove(const position &p) override;  // This was missing.
};

编辑:

如果我没记错的话,所有派生类都必须实现抽象函数

这是不正确的。您可能希望king是一个抽象类。与其他类成员一样,省略上面的声明会告诉编译器 king::canMove 应该继承自 figure::canMove - 它仍然应该是纯虚拟的。

这就是为什么你需要上面的声明。

【讨论】:

  • 看到这个被标记为 C++11,函数应该声明为virtual bool canMove(const position &p) override;
  • 哦,我的错,它只在 king.h 中声明过一次。如果方法是抽象的,为什么我需要再次声明它?如果我没记错的话,所有派生类都必须实现抽象函数。
  • @TomášČerník 在 C++ 中,如果您要覆盖具有不同实现的函数,则需要在标头中显式声明它,无论其抽象与否。这是因为,.C 文件中的实际实现可能在不同的库中。所以对于使用头部编译的代码,它必须知道它会在某个地方实现
  • 哦,我明白了!谢谢!
  • @TomášČerník 乐于助人。祝你好运!
【解决方案2】:

正如错误消息所说,您尚未声明方法canMove()。只需在king 类中声明即可

namespace figure
{
   class king : public figure
   {
   public:
       bool canMove(const position &p); 
   };
}

【讨论】:

    【解决方案3】:

    如编译器消息所示,您需要在king 类中添加declare canMove(const position&)

    【讨论】:

      猜你喜欢
      • 2021-01-06
      • 1970-01-01
      • 1970-01-01
      • 2017-06-06
      • 2021-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-14
      相关资源
      最近更新 更多