重写和继承
问题描述:
我有一个基类(Tableau)与一个函数(称为更新),并在该函数内,我调用另一个函数称为updateCustom。重写和继承
我想用我的JeuTaquin类来增强我的Base类,并且能够覆盖JeuTaquin中的updateCustom函数。因此,在我主要使用JeuTaquin对象调用函数更新时,我想从JeuTaquin开始我的updateCustom,但我不知道该怎么做!
这里是内部的Tableau我的更新功能:
template<class T>
void Tableau<T>::update()
{
int p1 = 1, p2 = 1;
int currentTurn = 1;
while(currentTurn!=tour || tour == 0){
cout<<*this<<endl;
updateCustom(getInput()); //HERE I CALL MY UPDATECUSTOM FUNCTION
if(p2 == 1)
computerTurn();
else
cout<<"player 2 game end"<<endl;
p1 = endTurn(plateau1);
p2 = endTurn(plateau2);
if(endCheck(p1))
break;
currentTurn++;
}
cout<<"game ended"<<endl;
}
在我的课的画面,我的功能updateCustom是空的(但声明)。在我JeuTaquin类,我重写我的updateCustom功能如下:(但它其实并不重要,看看这是什么函数内)
template<class T>
void Tableau<T>::updateCustom(char input)
{
int i, j;
Case<T> *neighbours;
while(true)
{
neighbours = Tableau<T>::checkNeighbours(Tableau<T>::plateau1, i, j);
if(input == 'z' && neighbours[0] !=nullptr)
{
swap(plateau1[i][j],plateau1[i-1][j]);
cout<<"Mouvement OK"<<endl;
break;
}
else if(input == 'd' && neighbours[1] !=nullptr)
{
swap(plateau1[i][j],plateau1[i][j+1]);
cout<<"Mouvement OK"<<endl;
break;
}
else if(input == 's' && neighbours[2] !=nullptr)
{
swap(plateau1[i][j],plateau1[i+1][j]);
cout<<"Mouvement OK"<<endl;
break;
}
else if(input == 'q' && neighbours[3] !=nullptr)
{
swap(plateau1[i][j],plateau1[i][j-1]);
cout<<"Mouvement OK"<<endl;
break;
}
cout<<"Mouvement IMPOSSIBLE"<<endl;
}
}
我无法找到互联网上的任何提示,当我跑我的更新函数与JeuTaquin对象一起使用,它从我的父类中运行我的空updateCustom,而不是从我的子类(JeuTaquin)中更新我的updateCustom。谢谢你的帮助。
答
我在我的updateCustom函数中添加了虚函数(仅在我的.h中),它的工作原理!当我重新更新定制,I型
void JeuTaquin<T>::updateCustom(char input)
代替
void Tableau<T>::updateCustom(char input)
是''updateCustom' virtual'? – Unimportant
不,updateCustom不是虚拟的 –
嗯,应该是,读了'虚拟'。 – Unimportant