初始化类对象数组c ++

时间:2013-11-16 15:41:25

标签: c++ class initialization

我正在尝试在.h和.cpp文件中初始化一个类对象数组。我最初在.h文件中声明它(game_map [12]),如下所示:

    #include <string>

    using namespace std;

    class Game {

    public:
        Game();
        ~Game();
        void test();
        void InitializeMap(Game &game);

    private:
        class Room {
        public:
            Room (string desc);
            Room();
            ~Room();
            void PrintDesc(Room &current);
            void SetDirection(int array_index, Room &current);

            string description;
            static int adjacent[3];rooms.
            static string direction[4];
        };

static Room game_map[12]; //Here is my array declaration
};
.
.
.
.

然而,当我尝试在实现文件中初始化game_map时......

#include "Game.h"

using namespace std;

/*Public members*/
Game::Game(){}
Game::~Game(){}
/*Private members*/

Room Game::game_map[12] = {Room("scary")}; //trying to initialize here
.
.
.
/*Room*/

int Game::Room::adjacent[] = {-1,-1,-1};
string Game::Room::direction[] = {"-1","-1","-1","-1"};

Game::Room::Room() {}

Game::Room::Room(string descript) {
    description = descript;
}


Game::Room::~Room() {}

 .
 .
 .

我得到一个错误,说Room未定义,尽管右侧的Room构造函数似乎被识别。我已经尝试在Room构造函数之后放置声明,但这并没有解决问题。有人能告诉我这里发生了什么吗?

谢谢!

2 个答案:

答案 0 :(得分:3)

喜欢这个

Game::Room Game::game_map[12] = {Room("scary")}; //trying to initialize here

^^^^^^ add Game:: here

我不喜欢所有静态成员的外观。清楚标志你的设计是错误的。

答案 1 :(得分:1)

我同意john使用静态的其他评论,但我确实得到了以下工作,我认为这就是你所追求的。我将让您了解需要私密化的细节。

以下是我设置课程的方法:

game.h:

#include "room.h"
class Game
{
public:
    Game();
    ~Game();
    void test();
    void InitializeMap(Game &game);
    static Room game_map[12];
};

game.cpp:

#include "game.h"
Game::Game() {}
Game::~Game() {}
Room Game::game_map[12] = {Room("scary")}; //initialize here

room.h:

#include <string>
class Room
{
public:
    Room (std::string desc);
    Room();
    ~Room();
    void PrintDesc(Room &current);
    void SetDirection(int array_index, Room &current);

    std::string description;
    static int adjacent[3];  // rooms.
    static std::string direction[4];
};

room.cpp:

#include "room.h"
Room::Room() {}
Room::~Room() {}
Room::Room(std::string descript) {
    description = descript;
}
int Room::adjacent[] = {-1,-1,-1};
std::string Room::direction[] = {"-1","-1","-1","-1"};

然后你可以在main.cpp中测试它:

#include <iostream>
#include "game.h"
#include "room.h"

int main()
{
    Game aGame;
    Room *rooms = new Room[12];
    rooms = aGame.game_map;

    std::cout << rooms[0].description << std::endl;

    delete [] rooms;

    return 0;
}

输出:

scary