【问题标题】:Base operand of '->' has non-pointer type vector<object*>'->' 的基操作数具有非指针类型 vector<object*>
【发布时间】:2017-12-06 23:30:56
【问题描述】:
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()
}

如您所见,我正在尝试使用指向指针向量的指针。但是在尝试访问向量时获取非指针类型 为什么我无法访问成员函数?

【问题讨论】:

  • 我确定它有一个副本,但我无法终生找到一个完全相同的副本。但是,相关:stackoverflow.com/questions/6946217/pointer-to-a-vector .
  • currentPlayer[i]“有效”,因为指针算法。你需要(*currentPlayer)[i]。并且 for 循环中的条件将失败;你需要for(int i = 0; i &lt; currentPlayer-&gt;size(); ++i)
  • 停止使用指针会轻松很多
  • 此代码一定是错误的:currentPlayer.size() 无效。您的部分代码希望 currentplayer 成为向量,其他部分希望成为指向向量的指针。是哪个?

标签: c++ pointers stdvector


【解决方案1】:

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

currentPlayer[i]->memberFunctionOfPiece();

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

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

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

【讨论】:

  • (*currentPlayer)[i]-&gt;memberFunctionOfPiece();
【解决方案2】:

你也可以在 STL 容器上使用 ranged for 循环

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多