継承された関数に問題があり、なぜそれがそのように動作しているのか理解できないようで、SO に関する他の質問で答えを見つけることができませんでした。
私は小さなゲームに取り組んでおり、継承された関数はプレーヤーとオブジェクト間の相互作用を担当しています。プレーヤーが「障害物」のさまざまな子クラスのいずれかが既に存在するスペースに移動しようとすると、そのオブジェクトの「Bool GetMove」メソッドを呼び出すと、独自のルールが実行され、ゲームがプレイヤーをスペースに配置できる場合は True が返され、配置できない場合は False が返されます。
これは、基本クラスのヘッダーとその getmove メソッドです。
class Obstacle
{
public:
const char* id;
Obstacle* _properlyinitialized; //a pointer that points to the object itself, required by the teacher who gave the assignment.
string Name;
mutable bool Moveable;
int x;
int y;
Obstacle();
Obstacle(string Name, bool Moveable, int x, int y);
virtual ~Obstacle();
bool properlyInitialized();
friend std::ostream& operator<<(std::ostream& stream, Obstacle& Obstacle);
virtual bool getmove(const char*, std::vector<std::vector<std::vector<Obstacle> > >&);
virtual void leavetile(std::vector<std::vector<std::vector<Obstacle> > >&);
};
bool Obstacle::getmove(const char* direction,std::vector<std::vector<std::vector<Obstacle> > >& _board){
cout << "wrong getmove" << endl; //this method should never be called.
return true;
};
継承されたクラスの 1 つとその getmove メソッド:
class Barrel: public Obstacle
{
public:
Barrel():Obstacle(){};
Barrel(string Name, bool Moveable, int x, int y);
~Barrel(){};
bool getmove(const char*, std::vector<std::vector<std::vector<Obstacle> > >&);
void leavetile(std::vector<std::vector<std::vector<Obstacle> > >&);
};
bool Barrel::getmove(const char* direction,std::vector<std::vector<std::vector<Obstacle> > >& _board){
cout << "barrel getmove" << endl;
if(strcmp(direction, "OMHOOG") == 0){ //what direction to move?
if(_board[this->x][this->y-1][0].properlyInitialized()){ //is that object already inhabited by an object?
if(_board[this->x][this->y-1][0].Moveable){ //can the object be moved?
if(_board[this->x][this->y-1][0].getmove(direction, _board){//move the object
_board[this->x][this->y-1][0] = *this; //move the barrel
_board[this->x][this->y-1][0]._properlyinitialized = &_board[this->x][this->y-1][0];
return true; //return true
}
else{
return false; //an object is in the way, the barrel can't be moved
}
}
else{
return false; //an object is in the way, the barrel can't be moved
}
}
else{
_board[this->x][this->y-1][0] = *this; //move the barrel
_board[this->x][this->y-1][0]._properlyinitialized = &_board[this->x][this->y-1][0];
return true; //return true
}
} //This is for direction "up", i left the other directions out because they're almost equal.
メソッドは次のように呼び出されます。
//"this" is a board object
if(this->playfield[this->_player->x][(this->_player->y)-1][0].getmove(direction, this->getBoard())){
//do some stuff
}
Obstacle オブジェクトを純粋な仮想オブジェクトに変更することを検討しましたが、他の場所にダミーの「Obstacle」オブジェクトが必要なので、これはオプションではありません。