저는 C++을 처음 사용하기 때문에 약간의 프로젝트를 통해 자신을 향상 시키기로했습니다. 나는 단위어떻게 가상 클래스의 벡터를 만들 수 있습니까?
#include <list>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <stdlib.h> /* abs */
using namespace std;
// Each unit class represent a chess unit
class Unit{
protected:
int currentX;
int currentY;
string side;
public:
Unit();
Unit(string sideplay, int Xpos,int Ypos)
{
currentX=Xpos; currentY= Ypos;side=sideplay;
}
int getX()
{
return currentX;
}
int getY()
{
return currentY;
}
string getside()
{
return side;
}
void setpos(int newX,int newY) //set new position
{
currentX=newX;
currentY=newY;
}
bool validmove(vector<Unit> unitlist ,string sidepick,int Xpos,int Ypos)
{ int i=0;
while(i != 3)
{ int X=unitlist[i].getX();
int Y=unitlist[i].getY();
string sidetemp= unitlist[i].getside();
if ((X==Xpos)&&(Y==Ypos)&&(sidetemp==sidepick))
{
return false;
}
else if ((X==Xpos)&&(Y==Ypos)&&(sidetemp!=sidepick))
{ //unitlist[i]=NULL;
return true;
}
i++;
}
return true;
}
virtual void moveunit(vector<Unit> unitlist ,int nextX,int nextY);
};
class King: public Unit{
public:
King(string sideplay, int Xpos,int Ypos):Unit(sideplay,Xpos,Ypos)
{}
void moveunit(vector<Unit> unitlist ,int nextX,int nextY){
int diffX=abs(nextX-currentX);
int diffY=abs(nextY-currentY);
if ((diffX==1)||(diffY==1))
{ if (validmove(unitlist,side,nextX,nextY))
{
setpos(nextX,nextY);}
}
}
};
에서 상속 된 클래스 단위 및 클래스 왕 간단한 체스 프로그램을 작성하려고 여기 내 주요입니다 :
int main()
{
vector<Unit> chessunit;
chessunit.push_back(King("white",3,1));
chessunit.push_back(King("black",3,2));
chessunit.push_back(King("white",4,1));
if (chessunit[0].validmove(chessunit,"white",3,2))
{
cout<<"hehe"<<endl;
}
chessunit[0].moveunit(chessunit,3,2);
int k= chessunit[0].getY();
cout<<k<<endl;
return 0;
}
내가 LNK에게가 계속 2001 오류 : 확인되지 않은 외부 기호를 내 가상 메서드 "moveunit". 버그를 어떻게 해결할 수 있습니까?
여기서 moveunit의 정의는 무엇입니까? 가상은 (순수하지 않다면) 메소드에 정의가 없다는 것을 의미하지 않습니다. –
먼저, (스마트 한) 포인터의 벡터를 사용해야합니다. 다형성은 포인터 (또는 참조)에서만 작동합니다. '개체 썰어보기'를보세요. 둘째, Unit :: moveunit * pure virtual * (look up)을 만든다. –
킹 클래스에서 정의합니다 : 이동이 유효한지 확인하는 역할을합니다. – user3875798