我不知道真的該怎麼尋找,試圖找到我的答案,所以請我重定向到任何相關的文章和我提前道歉。訪問私有數組從方法的對象在C++
我真的很新的C++,我試圖做一個3x3的CLI瓷磚遊戲。我可以將Tile對象分配給TileGame構造函數中的私有指針數組,並查看它們是否具有有效的內存地址(或者我認爲)。我的問題是當我運行方法嘗試訪問該數據時。它看起來像數組中的第一個元素有一個值,但其他人看起來很奇怪。我相信這是一件小事,但我對我做錯了什麼感到茫然。我也嘗試創建一個訪問器方法,但這似乎只會使事情複雜化。
#include <iostream>
using namespace std;
class Tile
{
private:
int position;
int tileID;
public:
Tile(int, int);
};
// tile constructor
Tile::Tile(int p, int id) : position(p), tileID(id) {}
class TileGame
{
private:
const int MAX_TILES;
Tile* tiles[];
public:
TileGame();
void shuffle();
};
// game constructor
TileGame::TileGame() : MAX_TILES(8)
{
Tile* tiles[MAX_TILES];
for (int i = 0; i < MAX_TILES; i++)
{
tiles[i] = new tile(i, i);
}
// spit out the addresses for each
cout << endl << "From TileGame(): " << endl;
for (int i = 0; i < MAX_TILES; i++)
{
cout << tiles[i] << endl;
}
}
void TileGame::shuffle()
{
// spit out the addresses for each
cout << endl << "From TileGame(): " << endl;
for (int i = 0; i < MAX_TILES; i++)
{
cout << tiles[i] << endl; // <-- This seems to be the problem
}
}
int main()
{
TileGame* game = new TileGame();
game->shuffle();
}
這應該編譯(我不得不重新輸入,所以我希望我沒有犯錯),我得到的輸出是一樣的東西:
From TileGame():
0x7f9349c03aa0
0x7f9349c03ab0
0x7f9349c03ac0
0x7f9349c03ad0
0x7f9349c03ae0
0x7f9349c03af0
0x7f9349c03b00
0x7f9349c03b10
From shuffle():
0x7fff9502752c
0x100
0
0
0
0
0
0
我到達這個點的時候通過嘗試訪問tiles[]
值,我不斷收到seg故障。思考?
如果您將8大小分配給2d數組,爲什麼不在類中聲明它。 –
您的代碼不能編譯。 – japreiss