C ++打印2d数组

时间:2016-12-20 15:22:46

标签: c++ arrays

我试图在ObjectOrientedProgramming中创建名为“DungeonCrawl”的基于CommandLine的游戏...... 我创建了一个标题&源文件,然后我在头文件中声明了函数和类,并且定义在源文件中。

问题:当我使用2 for循环打印电路板时,在Void函数中,它会打印一些随机整数而不仅仅是0 ...

打印后的结果:

0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 1303831201 100681557 
1606416496 32767 17 0 1 0 104 1 1606581343 32767 
1606416256 32767 1606423158 32767 1606416280 32767 1606416280 32767 1 0 
1606416304 32767 0 1 0 0 1606416320 32767 0 0 
0 0 0 0 0 0 0 0 1606416288 32767

这是头文件:

#ifndef dungeoncrawl_hpp
#define dungeoncrawl_hpp
#include <iostream>
#include <stdio.h>

using namespace std;

class dungeoncrawl {
public:
    dungeoncrawl();
    void drawBoard();
    ~dungeoncrawl();
private:
    int board[10][10];
    uint8_t player_pos[0][0], enemy_pos[0][0];

};

#endif /* dungeoncrawl_hpp */

这是源文件:

#include "dungeoncrawl.hpp"

// Constructor
class dungeoncrawl::dungeoncrawl {
    int board[10][10] = {
        {0,0,0,0,0,0,0,0,0,0},
        {0,0,0,0,0,0,0,0,0,0},
        {0,0,0,0,0,0,0,0,0,0},
        {0,0,0,0,0,0,0,0,0,0},
        {0,0,0,0,0,0,0,0,0,0},
        {0,0,0,0,0,0,0,0,0,0},
        {0,0,0,0,0,0,0,0,0,0},
        {0,0,0,0,0,0,0,0,0,0},
        {0,0,0,0,0,0,0,0,0,0},
        {0,0,0,0,0,0,0,0,0,0}
    };
};

// Con-&-Destructor
dungeoncrawl::dungeoncrawl(){}
dungeoncrawl::~dungeoncrawl(){}

void dungeoncrawl::drawBoard(){
    for(int i = 0; i < 10; i++){
        for(int j = 0; j < 10; j++){
            cout << board[i][j] << " ";
        }
        cout << endl;
    }
};

1 个答案:

答案 0 :(得分:1)

您的代码中有两个错误。起初:

uint8_t player_pos[0][0], enemy_pos[0][0];

gcc提供零长度数组作为扩展。在你的情况下它没用。

其次:

class dungeoncrawl::dungeoncrawl {

它不是一个委托人。如果要初始化类成员,可以在构造函数中执行此操作。比如这里:

// Constructor
dungeoncrawl::dungeoncrawl(){
    for(int i = 0; i < 10; i++){
        for(int j = 0; j < 10; j++){
            board[i][j] = 0;
        }
    }
}

或者,例如,您可以将数组声明为static:

//dungeoncrawl.hpp
private:        
     static int board[10][10];

//dungeoncrawl.cpp
int dungeoncrawl::board[10][10] = {
                  {0,0,0,0,0,0,0,0,0,0},
                  {0,0,0,0,0,0,0,0,0,0},
                  {0,0,0,0,0,0,0,0,0,0},
                  {0,0,0,0,0,0,0,0,0,0},
                  {0,0,0,0,0,0,0,0,0,0},
                  {0,0,0,0,0,0,0,0,0,0},
                  {0,0,0,0,0,0,0,0,0,0},
                  {0,0,0,0,0,0,0,0,0,0},
                  {0,0,0,0,0,0,0,0,0,0},
                  {0,0,0,0,0,0,0,0,0,0}
};