Целое число члена объекта C ++ имеет смешное значение (WTF) - PullRequest
3 голосов
/ 06 марта 2011

Это для игры в покер, и у меня есть класс PokerTable, определенный в PokerTable.h

#include <iostream>
using namespace std;
class PokerTable
{
private:
 int numPlayers;
 int numPlaying;
 int dealerPos;
 int bigBlind;
 int potSize;
 int betSize;
 bool flop;
 bool turn;
 bool river;

 public:
 //constructors
 PokerTable();
 PokerTable(int,int,int,int,int,bool,bool,bool);

 //getters
 int getNumPlayers(){return numPlayers;};
 int getDealerPos(){return dealerPos;};
 int getBigBlind(){return bigBlind;};
 int getNumPlaying(){return numPlaying;};
 int getPotSize(){return potSize;};
 int getBetSize(){return betSize;};
 bool getFlop(){return flop;};
 bool getTurn(){return turn;};
 bool getRiver(){return river;};
 //void buttonShow(int);


 //setters
 void setBetSize(int inBetSize){betSize = inBetSize;};
 void setBigBlind(int inBigBlind){bigBlind = inBigBlind;};
 void setNumPlaying(int inNumPlaying){numPlaying = inNumPlaying;};
 void setPotSize(int inPotSize){potSize = inPotSize;};
 void setFlop(bool inFlop){flop = inFlop;};
 void setTurn(bool inTurn){turn = inTurn;};
 void setRiver(bool inRiver){river = inRiver;};
 void setNumPlayers(int inPlayers){numPlayers = inPlayers;};
 void setDealerPos(int inDealerPos){dealerPos = inDealerPos;};
};
PokerTable::PokerTable()
{
 numPlayers = 9;
 numPlaying = 9;
 dealerPos = 1;
 bigBlind = 20;
 flop = false;
 turn = false;
 river = false;
}
PokerTable::PokerTable(int playerNum, int playingCount, int posDealer, int blindBig,int inPotSize, bool inFlop,bool inTurn,bool inRiver)
{
 numPlayers = playerNum;
 numPlaying = playingCount;
 dealerPos = posDealer;
 potSize = inPotSize;
 bigBlind = blindBig;
 flop = inFlop;
 turn = inTurn;
 river = inRiver;
}

В моем списке наблюдения pokerTable.numPlayers имеет случайное значение до 4 миллионов, прежде чем я даже выполню следующую строкукода.

PokerTable aPokerTable(9,9,1,20,30,false,false,false);

и после этого pokerTable в моем списке наблюдения:

-       aPokerTable { numPlayers=2990892 numPlaying=9 dealerPos=9 ...}  PokerTable
        betSize 30  int
        bigBlind    1   int
        dealerPos   9   int
        flop    false   bool
        numPlayers  2990892 int
        numPlaying  9   int
        potSize 20  int
        river   false   bool
        turn    false   bool

Может кто-нибудь сказать мне, почему все значения не являются такими, какими я их объявил ??!? !!И как я могу это исправить?

Это Form1.h

#pragma once
#include "PokerTable.h"
#include "Card.h"
#include <time.h>
#include "PokerPlayer.h"
#include <fstream>
#include <string>
#include <sstream>

//global variables
//TODO make players start from 0
int firstPlayer;
int deck[52];
int nextCard=0;
PokerTable aPokerTable(9,9,1,20,30,false,false,false);
PokerPlayer players[9]; //however many players
ofstream gameLog;
/*
void setTable()
{
    aPokerTable.setNumPlayers(9);
    aPokerTable.setNumPlaying(9);
    aPokerTable.setDealerPos(1);
    aPokerTable.setBigBlind(20);
    aPokerTable.setPotSize(30);
    aPokerTable.setBetSize(20);
    aPokerTable.setFlop(false);
    aPokerTable.setTurn(false);
    aPokerTable.setRiver(false);

}
*/
string convertInt(int number) //convert to string
{
   stringstream ss;//create a stringstream
   ss << number;//add number to the stream
   return ss.str();//return a string with the contents of the stream
}

void createPlayers()
{
//  aPokerTable.setNumPlayers(9);
    for(int x=0;x<=(aPokerTable.getNumPlayers()-1);x++)
    {
        players[x] = *(new PokerPlayer(1000,(aPokerTable.getDealerPos())+1,false,0,1));//1000 chips, position i+1, not folded
    }
}



void playRound()
{
    int action;
    for(int playerTurn = firstPlayer; playerTurn <= aPokerTable.getNumPlayers()+firstPlayer;  playerTurn++)
    {
        if(players[playerTurn].getFold() == false)
        {
            if(aPokerTable.getNumPlaying() == 1)
            {
                players[playerTurn].setChipStack(players[playerTurn].getChipStack() + aPokerTable.getPotSize()); //player wins pot
            }
            else //there is more than one person playing
                {
                action = players[playerTurn].action(); //0 is check/fold, value is call/bet/raise,
                if(action > aPokerTable.getBetSize())
                {
                    aPokerTable.setBetSize(action);
                    aPokerTable.setPotSize(aPokerTable.getPotSize() + action);
                    playerTurn = playerTurn - aPokerTable.getNumPlayers();
                }
                else if (action == aPokerTable.getBetSize()) //call
                {
                    aPokerTable.setPotSize(aPokerTable.getPotSize() + action);
                }
                else //action < aPokerTable.betSize
                {
                    players[playerTurn].setFold(true);
                    aPokerTable.setNumPlaying(aPokerTable.getNumPlaying()-1); //removes player from playing tally
                }
            }
        }
    }
}


void randomDeck()
{
    int random_integer;
    int tempCard;
    //srand((unsigned)time(0));
    for(int j=0;j<=51;j++)
    {
        deck[j] = j;
    } 

    for(int i=51; i>=1; i--)
    {
        random_integer = rand()%(i); //a random number between 0 and i
        tempCard = deck[i];
        deck[i] = deck[random_integer]; //put the random card from unshuffled deck into slot i of the deck
        deck[random_integer] = tempCard; //put whatever was at slot i into the random slot
    }

}

void dealCards()
{
    for(int j=1;j<=aPokerTable.getNumPlayers();j++)
    { 
        players[j].setCard1(deck[nextCard]);
        nextCard++;
        players[j].setCard2(deck[nextCard]);
        nextCard++;
    }
}

void playPreFlop()
{
    aPokerTable.setBetSize(aPokerTable.getBigBlind());
    aPokerTable.setFlop(false); //it is before the flop
    aPokerTable.setTurn(false);
    aPokerTable.setRiver(false);
    randomDeck(); //shuffle cards
    dealCards();
    firstPlayer = (aPokerTable.getDealerPos() + 3)%(aPokerTable.getNumPlayers()); // first player is left of blinds between 0 and numplayers
    playRound();
}


void playFlop()
{
    aPokerTable.setFlop(true);
    firstPlayer = (aPokerTable.getDealerPos())%aPokerTable.getNumPlayers(); // first player is left of dealer between 0 and numplayers
    aPokerTable.setBetSize(0);
    playRound();
}
void playTurn()
{
    aPokerTable.setTurn(true);
    firstPlayer = (aPokerTable.getDealerPos())%aPokerTable.getNumPlayers(); // first player is left of dealer between 0 and numplayers
    aPokerTable.setBetSize(0);
    playRound();
}
void playRiver()
{
    aPokerTable.setRiver(true);
    firstPlayer = (aPokerTable.getDealerPos())%(aPokerTable.getNumPlayers()); // first player is left of dealer between 0 and numplayers
    aPokerTable.setBetSize(0);
    playRound();
    if(aPokerTable.getNumPlaying() >=2)
        {
        //showDown();
        }
}
/*
void showDown()
{

}
*/

Это pokerPlayer.h

using namespace std;
    class PokerPlayer
    {
    private:
        int chipStack,position;
        bool fold;
        int card1,card2;
    public:
        //constructors
        PokerPlayer();
        PokerPlayer(int,int,bool,int,int);

        //getters
        int getChipStack() {return chipStack;}
        int getPosition() {return position;}
        int getCard1(){return card1;}
        int getCard2(){return card2;}
        bool getFold(){return fold;}

        //setters
        void setChipStack(int inChips){chipStack = inChips;}
        void setPosition(int inPos){position = inPos;}
        void setCard1(int inCard1){card1 = inCard1;}
        void setCard2(int inCard2){card2 = inCard2;}
        void setFold(bool inFold){fold = inFold;}

        int action();
    };

    PokerPlayer::PokerPlayer()
    {
        chipStack = 1000;
        position = 0;
        fold=false;
        card1 = 0;
        card2 = 1;
    }
    PokerPlayer::PokerPlayer(int inChipStack,int inPos, bool inFold, int inCard1, int inCard2)
    {
        chipStack = inChipStack;
        position = inPos;
        fold = inFold;
        card1 = inCard1;
        card2 = inCard2;
    }
    int PokerPlayer::action()
    {
        return 0;
    }

Ответы [ 4 ]

2 голосов
/ 06 марта 2011

aPokerTable {numPlayers = 2990892 numPlaying = 9 дилеров = 9 ...}

Обратите внимание, что ДилерПос получил значение 9, это тоже неправильно. Если вы посмотрите внимательно, вы увидите, что все сдвинуто на 4 байта.

Две возможные причины. Отладчик мог выбрать неверный адрес для aPokerTable, фактический адрес минус 4. Это маловероятно. Или существует несоответствие между определением класса PokerTable, как видно из pokertable.cpp, и другими файлами .cpp, которые #include включают файл pokertable.h Где pokertable.cpp видел дополнительного члена перед членом numPlayers. Возможно, вы отредактировали заголовок и удалили этого участника, но в итоге по какой-то таинственной причине не перекомпилировали pokertable.cpp. Build + Rebuild, чтобы исправить. Паникуйте немного, если это действительно работает.

1 голос
/ 06 марта 2011

Я не могу восстановить его, потому что у меня нет полного кода.Однако случайное значение около 4 миллионов звучит как указатель.Когда вы сохраняете или извлекаете переменную-член, возможно, вы не отменяли ссылку на указатель.Пожалуйста, опубликуйте остаток кода, чтобы мы могли проверить, так ли это.

1 голос
/ 06 марта 2011

players[x] = *(new PokerPlayer(...));

Это утечка памяти.Что вы, вероятно, хотите:

players[x] = PokerPlayer(1000,(aPokerTable.getDealerPos())+1,false,0,1);
1 голос
/ 06 марта 2011

Это потому, что в C ++ до вызова конструктора переменная использует значение, которое она уже содержит в своей ячейке памяти, что является "случайным" значением

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...