2014-05-24 50 views
0

仍在學習C++,但我在這裏卡住了,我得到了這些類:多類編譯錯誤

Case.cpp:

#include "../inc_bomber/Case.hh" 

Case::Case() 
{ 

} 

Case::~Case() 
{ 

} 

Case.hh:

#ifndef _CASE_HH_ 
# define _CASE_HH_ 

enum Type 
    { 
    FLOOR, 
    WALL, 
    BOMB, 
    BLOCK, 
    PLAYER1, 
    PLAYER2, 
    BOT, 
    BONUS, 
    }; 

class Case 
{ 
private: 

public: 
    Case(); 
    virtual ~Case(); 

    virtual Type getType() const = 0; 
    virtual void action() = 0; 
    virtual int getPos(int x, int y); 
}; 

#endif /* CASE_HH_ */ 

我使用這些虛擬類如下:

Player1.hh:

#ifndef _PLAYER1_HH_ 
# define _PLAYER1_HH_ 

#include "Case.hh" 
#include "Map.hh" 

class Player1 : public Case 
{ 
private: 
    int x; 
    int y; 

public: 
    Player1(); 
    ~Player1(); 
    virtual Type getType() const; 
    virtual void action(); 
    virtual void print_stuff(); 
    virtual int getPos(int x, int y); 
}; 

#endif /* _PLAYER1_HH */ 

在編譯的時候我得到這個錯誤,我猜IM混淆了虛擬的使用,但仍然沒有找到我的錯誤

g++ -Wall -Wextra -ansi -g3 -I includes/ -c src_bomber/Case.cpp -o src_bomber/Case.o 
g++ -o bomber src_bomber/main.o src_bomber/GameMain.o src_bomber/Map.o src_bomber/Case.o src_bomber/Floor.o src_bomber/Block.o src_bomber/Wall.o src_bomber/Bomb.o src_bomber/Bot.o src_bomber/Player1.o src_bomber/Player2.o -Llibs/ -lgdl_gl -lGL -lGLEW -ldl -lrt -lfbxsdk -lSDL2 -lpthread -Wl,-rpath=./libs/ 
src_bomber/Case.o:(.rodata._ZTV4Case[vtable for Case]+0x30): undefined reference to `Case::getPos(int, int)' 
collect2: ld returned 1 exit status 
make: *** [bomber] Error 1 

回答

2

Case::getPos(int, int);沒有被標記爲純虛(= 0),同比所以必須有一個提供的實現(如果您曾致電getPos(int,int)參考Case)。您應該將= 0添加到Case::getPos(int,int)的聲明中,如同對所有其他虛擬成員函數Case所做的那樣,或者您應該添加Case::getPos(int,int)的實現,就像您對Case的構造函數和析構函數所做的那樣。

+0

似乎工作很棒thx :)我不明白爲什麼我應該把這些= 0每次最後是這是一個cpp技巧? – Saxtheowl

+0

當你把= 0時,你必須在派生類中定義和實現函數。這些被稱爲純虛函數。 – vsoftco

+0

這是[將函數定義爲純虛函數的語法](http://en.cppreference.com/w/cpp/language/abstract_class)。這不是一個「竅門」,而只是語言的一部分。純粹的虛函數不需要被定義(除了析構函數),因爲它很少有被調用的原因。 – Mankarse