我正在用随机的多米诺骨牌填充两个玩家的手,没有问题。当我将结构发送到另一个类时,我再也无法访问玩家的手了。
using namespace std;
struct player {
int playerNum;
vector < pair <int, int>> hand;
};
vector < pair <int, int>> availablePieces;
void Player::createHand(vector < pair <int, int>> &multiVector, player* player) {
srand(time(NULL)); // rand seed
int ranNumb;
//fill players' hand
for (int i = 0; i < 10; i++) {
ranNumb = rand() % multiVector.size();
player[0].hand.push_back(multiVector[ranNumb]);
multiVector.erase(multiVector.begin() + ranNumb);
ranNumb = rand() % multiVector.size();
player[1].hand.push_back(multiVector[ranNumb]);
multiVector.erase(multiVector.begin() + ranNumb);
}
}
setAvailablePieces(multiVector);
void Player::createPlayers(vector < pair <int, int>>& multiVector) {
struct player* domiPlayer = new struct player[2];
domiPlayer[0].playerNum = 1;
domiPlayer[1].playerNum = 2;
createHand(multiVector, domiPlayer);
}
Game gameObj;
gameObj.API(player, availablePieces);
游戏标题:
using namespace std;
class Game
{
public:
void API(struct player* player, vector < pair <int, int>> &availablePieces);
private:
void playGame(player* player, vector < pair <int, int>>& availablePieces);
};
游戏类:
void Game::playGame(player* player, vector < pair <int, int>>& availablePieces) {
cout << player[0].hand[0].first << endl;
}
void Game::API(player* player, vector < pair <int, int>> &availablePieces) {
playGame(player, availablePieces);
}
在功能playGame中,我无法访问单个玩家的手。我收到错误消息:表达式必须是指向完整对象类型的指针。
答案 0 :(得分:0)
我的最初答案不正确(对不起)。但是,在再次查看之后,我认为我看到了您的问题(除了{@TedLyngmo提到的undefined
完成后您的player
对象的泄漏)。
创建createPlayers
时,请再次使用players
。由于您已经将struct
定义为结构,因此不需要。参见下文,在此我为您的代码制作了一个更简单的示例,初始化player
并将其存储在players
类中:
Game
这解决了#include <stdio.h>
struct player {
int test = 2;
};
class Game {
public:
Game(const int nPlayers);
void playGame();
private:
player *players;
};
Game::Game(const int nPlayers) {
players = new player[nPlayers];
}
void Game::playGame() {
printf("%d\n", players[0].test);
}
int main() {
const int nPlayers = 2;
Game game(nPlayers);
game.playGame();
}
超出范围以及初始化players
时不再使用struct
的问题。我还省略了players
类,因为不清楚您发布的代码的来源。