2013-04-10 77 views
0

我有一个很奇怪的问题。命名空间中的抽象方法

我有3个文件:
figure.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 

king.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: error: no ‘bool figure::king::canMove(const position&)’ member function declared in class ‘figure::king’

我该怎么办? 非常感谢!

+2

命名空间和函数体不需要分号。 – chris 2013-04-10 23:30:38

+0

@chris - 作为回答 – 2013-04-10 23:46:14

+2

@ZacharyKniebel,我非常怀疑导致错误。 – chris 2013-04-10 23:47:15

回答

0

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

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

您需要声明该功能在class king

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

编辑:

All derived classes must implement abstract functions if I'm not mistaken

这是不正确。您可能希望将类king改为也是是抽象类。和其他类的成员一样,忽略上面的声明告诉编译器king::canMove应该从figure::canMove继承 - 它应该仍然是纯虚拟的。

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

+0

看到这个标签是C++ 11,函数应该声明为'virtual bool canMove(const position&p)override;' – 2013-04-11 00:23:38

+0

哦,我的错,它在king.h中只声明了一次。如果方法是抽象的,为什么我需要再次声明它?如果我没有弄错,所有派生类都必须实现抽象函数。 – Shin 2013-04-11 05:22:32

+0

@TomášČerník在C++中,如果您正在重写具有不同实现的函数,则需要在头中显式声明它是否与其摘要相关。这是因为,.C文件中的实际实现可能位于不同的库中。因此,对于使用头文件进行编译的代码,它必须知道它将在某处执行 – balki 2013-04-12 15:18:44

0

如编译器消息所示,您需要declarecanMove(const position&)里面的king类。