' - &gt;'的基本操作数具有非指针类型向量<object *>

时间:2017-12-06 23:30:57

标签: c++ pointers stdvector

std::vector<Piece*> player1, player2;

/* Filling player 1 and 2 vith piece 
   player1.push_back(new Piece()) */

std::vector<Piece*> *currentPlayer, *opponent;

currentPlayer = &player1;
opponent      = &player2

for(int i = 0; i < currentPlayer.size(); ++i)
{
    // This is where i get the error
    // error: base operand of '->' has non-pointer type 'std::vector<Piece*>'
    currentPlayer[i]->memberFunctionOfPiece()
}

正如您所看到的,我正在尝试使用指向指针向量的指针。但在尝试访问向量时获取非指针类型 为什么我无法访问会员功能?

2 个答案:

答案 0 :(得分:1)

问题是你试图在指针类型上使用方括号:

currentPlayer[i]->memberFunctionOfPiece();

你可以使用operator []甚至更好地使用at函数

currentPlayer->at(i)->memberFunctionOfPiece();

currentPlayer->operator[](i)->memberFunctionOfPiece();

答案 1 :(得分:0)

您还可以在STL容器上使用ranged for循环

for(auto&& player : *currentPlayer)
{
    player->memberFunctionOfPiece();
}