簡體   English   中英

C ++中對象的多維數組

[英]multidimensional array of objects in c++

我正在編寫作業(創建虛擬世界),遇到了一件我無法逾越的事情。 我有一個有機體課,它是所有未來繼承動物(動物等)的抽象,而世界類則代表這些對象的世界。 但是在后者中,我無法創建一系列有機體-存儲每個現有有機體的位置。

它會拋出:“語法錯誤:在'token2'之前缺少'token1'

我當時在想,這可能是相互關聯的(有機體引用了某些世界,某些世界想要創建生物體數組),但是默認構造函數正在解決該問題。

你能告訴我我監督了什么嗎? 提前致謝。

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();
};

C ++中沒有這種new Type[size1][size2]構造,但是您可以執行以下操作:

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;
    }
}

或只使用std::vector

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

或使用大小為size1 * size2單個std::vector並根據ij計算索引: index = i * size1 + j

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM