2013-04-10 72 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類。