C++中的虚函数问题

Saa*_*lah 0 c++ inheritance

AoA,我正在制作一个国际象棋的控制台游戏,但我坚持多态,下面是类和函数定义/*旧的部分//基类

class Piece         /*Parent class */
{
protected:
    Position* pCoord;
    std::string color;
    char symbol;
public:
    Piece(Position* Coord,std::string Color,char symbol);
    Position GetCurrentPos();
    std::string GetColor();
    void SetColor(std::string color);
    void Draw();
    virtual bool SetPos(Position* newPos){MessageBox(NULL,L"Virtual Running",L"Error",MB_OK); return true;};
    virtual ~Piece();
};

/* Inherited classes */
//Child classes
class Pawn: public Piece
{
private:
    std::vector<Position>* allowPos;
public:
    Pawn(Position* Coord,std::string Color,char symbol);
    ~Pawn();
    std::vector<Position>* GetThreatendFields();
    bool isValidMove(Position* newPos);
    bool SetPos(Position* newPos);
};
//Child classes
class Bishops: public Piece
{
private:
    std::vector<Position>* allowPos;
public:
    Bishops(Position* Coord,std::string Color,char symbol);
    ~Bishops();
    std::vector<Position>* GetThreatendFields();
    bool isValidMove(Position* newPos);
    bool SetPos(Position* newPos);
};
//Here is the implementation of child class function SetPos


   bool Pawn::SetPos(Position* newPos)
{
    bool isSet = false;

    this->pCoord = new Position();
    this->pCoord = newPos;
    isSet = true;
    MessageBox(NULL,L"Child function running",L"Yuhuu!",MB_OK);

    return isSet;
}


 class ChessBoard
{
private:
    Position ptr;       //dummy
    int SelectedPiece;
    vector<Piece> pPieceSet;
    bool isSelected;
public:
    ChessBoard();
    ~ChessBoard();
    void ShowPieces(Player *p1,Player *p2);
    void Draw();
    void MouseActivity();
    void Place(Piece& p);
};

//it just shows the peices acquired from player objects..dummy vector pointer
void ChessBoard::ShowPieces(Player* p1,Player* p2)
{
    std::vector<Piece>* vPiece = p1->GetPieces();
    for( int i=0;i<vPiece->size();i++ )
    {
        Piece& piece = vPiece->at(i);
        Place(piece);
        piece.Draw();
    }
    vPiece = p2->GetPieces();
    for( int i=0;i<vPiece->size();i++ )
    {
        Piece& piece = vPiece->at(i);
        Place(piece);
        piece.Draw();
    }
}
*/
/*new part
Run Code Online (Sandbox Code Playgroud)

我做了你说的

Player::std::vector<Piece*> *vPieceSet;
Player::Player(int turn)
{
    this->turn = turn%2;    
    this->vPieceSet = new std::vector<Piece*>;
}
void Player::Initialize()       //Initial and final ranges for position
{
    //Initialization of pieces to their respective position
    Position pos;
    Piece *pPiece;
    if( this->turn == 0 )
    {
        this->SetName("Player 1");

        for( int i=8;i<16;i++ )
        {
            pos.SetPosition(i);
            Pawn pPawn(&pos,"blue",'P');
            pPiece = &pPawn;

            this->vPieceSet->push_back(pPiece);
        }
   //other classes same as above
}

It runs fine at initialzation function(stores all classes fine) but when use function to get the vector object

std::vector<Piece*>* Player::GetPieces()
{
    std::vector<Piece*>* tPieces = this->vPieceSet;
    return tPieces;
}

//In main.cpp
it doesnot return the vector object
        Player p1(0),p2(1);
    p1.Initialize();
    p2.Initialize();      //initialization done perfectly while debugging

    vector<Piece*> *obj = p1.GetPieces();   //returns garbage
    Piece* pObj = obj->at(0);               //garbage

    cout<<pObj->GetColor();    //  garbage
Run Code Online (Sandbox Code Playgroud)

*/新部分

听起来我有另一个问题!

Joh*_*ing 7

当您使用多态时,您真正想要做的是实例化派生类型的对象,并通过指针或对基础对象的引用来调用该对象上的方法.

class Foo
{
public:
  virtual void DoIt () { cout << "Foo"; }
};

class Bar
:
  public Foo
{
public:
  void DoIt () { cout << "Bar"; }
};

int main()
{
  Foo* foo = new Bar;
  foo->DoIt(); // OUTPUT = "Bar"
  Foo& fooRef = *foo;
  fooRef.DoIt(); // OUTPUT = "Bar"
}
Run Code Online (Sandbox Code Playgroud)

为了使其工作,您需要使用指针或对象的引用.您无法使用基类创建对象的副本.如果您复制,您将切片对象.

int main()
{ 
  Foo* foo = new Bar;
  foo->DoIt(); // OK, output = "Bar"
  Foo fooCopy = *foo;  // OOPS!  sliced Bar
  fooCopy.DoIt(); // WRONG -- output = "Foo"
}
Run Code Online (Sandbox Code Playgroud)

在你的代码中,这个Piece类是多态的,在你的ChessBoard类中你有vector这个类:

class ChessBoard
{
private:
    vector<Piece> pPieceSet;
};
Run Code Online (Sandbox Code Playgroud)

由于这是对象本身的一个,而不是指向vectorPiece对象,因此Piece您在此处放置的任何内容都将被切片.你需要改为pPieceSet成为vector指针Piece:

vector <Piece*> pPieceSet;
Run Code Online (Sandbox Code Playgroud)

你还有其他问题Initialize,无论如何都需要重构.一方面,你有其他 vectorPiece对象,这里有两个问题.首先,它需要成为一个vector指针,其次,当你vector已经有一个与之相关的时候,为什么还需要另一个ChessBoard呢?我没有彻底检查你的代码,所以也许你确实需要它,但这似乎是一个错误.应该只有一个集合,在ChessBoard.

在你的Initialize方法中:

Piece *pPiece;
// ...
Pawn pPawn(&pos,"blue",'P');
pPiece = &pPawn;
vPieceSet.push_back(*pPiece);
Run Code Online (Sandbox Code Playgroud)

有几个问题.一,你正在推回一个切片的副本,Piece当你改变你vector的存储指针时,它将被修复.其次,如果您只是改变这样:

Piece *pPiece;
// ...
Pawn pPawn(&pos,"blue",'P');
pPiece = &pPawn;
vPieceSet.push_back(pPiece); // <-- not dereferencing
Run Code Online (Sandbox Code Playgroud)

您将遇到一个新问题,因为您将指针存储到本地(自动)变量.最好是这样做:

Piece* pPiece = new Pawn (...);
// ...
vPieceSet.push_back (pPiece);
Run Code Online (Sandbox Code Playgroud)

请不要忘记delete你的一切new.这最好通过使用智能指针而不是原始指针来处理.在C++ 03中我们有auto_ptr,但那些不能进入vector.相反,你需要使用Boost或其他东西,或者只是存储原始指针.在C++ 11中,我们现在有unique_ptr(首选)shared_ptr,它可以进入a vector.

在C++ 11中,这里最好的解决方案是将一个向量声明为:

vector <unique_ptr <Piece> > pPieceSet;
Run Code Online (Sandbox Code Playgroud)

...除非你有一些迫切需要使用shared_ptr.