简体   繁体   中英

multidimensional array of objects in c++

I'm writing assignment (creating virtual world) and I've encountered one thing I can't go over. I have class Organism which is an abstract for all the future inheriting ones (animals etc.) and class World which represents the world of these objects. In the latter I can't create an array of Organisms though - to store position of every existing organism.

It throws: "syntax error : missing 'token1' before 'token2'

I was thinking that maybe it has something to do with that it refers to each other (organism has reference to certain world and certain world wants to create array of organisms) but default constructor is solving that thing imo.

Could you tell what have I overseen? Thanks in advance.

World.h

#pragma once
class World
{
private:
    int sizeX;
    int sizeY;
    Organism * worldMesh;
public:
    World(int sizeX, int sizeY);
    void nextTurn();
    void drawWorld();
    int getWorldX();
    int getWorldY();
~World();
};

World.cpp

#include "stdafx.h"
#include "World.h"
#include <iostream>

using namespace std;

World::World(int sizeX, int sizeY)
{
    this->sizeX = sizeX;
    this->sizeY = sizeY;
    worldMesh = new Organism[sizeX][sizeY];
    for (int i = 0; i < sizeX; i++) {
        for (int j = 0; j < sizeY; j++) {
            worldMesh[i][j] = NULL;
        }
    }
} ....

Organism.h

#pragma once
#include "World.h"
#include "Position.h"


class Organism
{
protected:
    int strength;
    int initiative;
    Position * position;
    static World * world;
public:
    Organism();
    Organism(World * world);
    int randValue();
    virtual void spawn();
    virtual void action();
    virtual void collision();
    void kill();
    virtual ~Organism();
};

There is no such new Type[size1][size2] construction in C++, but you can do something like this:

int** mesh = new int*[size1];
for( int i = 0; i < size1; i++ ) {
    mesh[i] = new int[size2];
    for( int j = 0; j < size2; j++ ) {
        mesh[i][j] = 0;
    }
}

or just use std::vector

std::vector< std::vector<Type> > mesh;

or use single std::vector with size size1 * size2 and calculate index from i and j : index = i * size1 + j

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM