动态对象数组增加

时间:2015-03-30 08:40:46

标签: c++ arrays object dynamic allocation

我正在构建一个多米诺骨牌游戏并尝试制作一个能够将石头添加到堆中的功能。 这是Stone类:

class Stone
{
public:
    Stone(){ left = 0; right = 0; };
    Stone(int x, int y){ left = x; right = y; };
    void turnStone();
    bool comStones(const Stone&);
    void printOpen();
    void printClosed();
    friend class Pile;
    friend class Game;
private:
    int left, right;
};

这是桩类:

class Pile
{
public:
    Pile(){};
    Stone indexfun(int);
    void printOpen();
    void printClosed();
    void fillPile();
    void randPile();
    void addStone(Stone&);
    void remStone(Stone&);
    friend class Player;
    friend class Game;
private:
    Stone* list;
    int size=0;
};

现在,我为堆积添加石头而构建的功能是:

void Pile::addStone(Stone& newStone) {
    Stone* newList = new Stone[size + 1];
    int i;
    for (i = 0; i < size; i++)
    {
        newList[i] = list[i];
    }
    newList[i] = newStone;
    delete[] list;
    list = newList;
    size++;
}

当我尝试构建newlist数组时,它会让我退出程序。找不到原因。帮助任何人?

以前的函数和项目中的更多类:

class Game
{
public:
    Game(char*);
    void run();
private:
    Player human, computer;
    Pile box, table;
    int start, finish;
    void playerMove(int);
    void checkPile(int);
    bool checkMove(int,int);
    bool whosFirst();
    bool checkGame();
    void printTable();
};
class Player
{
public:
    Player(){};
    void addStone(Stone&);
    void remStone(Stone&);
    void printPile();
    Stone* searchStone();
    friend class Game;
private:
    char* name;
    Pile pie;
};
void Game::run() {
    cout << "starting the game" << endl;
    box.fillPile();
    box.size = 28;
    box.randPile();
    for (int i = 0; i < 7; i++)
    {
        human.addStone(box.list[i]);
        box.remStone(box.list[i]);
        computer.addStone(box.list[i]);
        box.remStone(box.list[i]);
    }
}
void Player::addStone(Stone& added) {
    pie.addStone(added);
}

int main()
{
    char name[80];
    cout << "enter your name" << endl;
    cin >> name;
    Game game(name);
    game.run();
}

1 个答案:

答案 0 :(得分:0)

也许将“list”变量名称更改为“list1”或类似的东西。 “list”是一个STL容器,就像vector一样。