M
M
Mark Berezovsky2020-11-06 12:20:42
C++ / C#
Mark Berezovsky, 2020-11-06 12:20:42

What if two classes use each other?

Faced such a situation that the field class and the snake class use each other, because the snake changes the matrix of the field, and the field creates a cycle of their movement (and also sends them the events of pressing the binds). But I can’t calm the compiler in any way, because in the headers of these classes they are included by themselves from each other. How to make it all work?

field.h

#include <vector>
#include "snake.h"


class Field {
    public:
        std::vector<std::vector<int>> matrix;
        std::vector<Snake*> snakes;
        int w, h;
        bool hasWalls = false;
        Field() {};
        Field(int w, int h) {};
        //
        // Returns all empty tile coordinates.
        //
        std::vector<std::pair<int, int>> getEmptyTiles() {};
        //
        // Placing food tile in random place.
        //
        void generateFood() {};
        //
        // Creating border of walls for matrix.
        //
        void generateWalls() {};
        //
        // Set empty tile for specific place.
        //
        void clear(int x, int y) {};
        //
        // Set any type of tile for specific place.
        //
        void set(int x, int y, int t) {};
        //
        // Returns tile at specific place.
        //
        int at(int x, int y) {};
        //
        // Start the game at current field.
        //
        void render(float pixelSize) {};
};

snake.h
#include <vector>
#include "field.h" // на данном моменте компилятор понимает, что что-то идет не так
#include "enums.h"


class Snake {
    public:
        std::vector<std::pair<int, int>> tiles;
        Field& field;
        int x, y;
        int length = 1;
        int direction, score = 0;
        bool alive = true;
        Snake(Field & f, int x, int y, int startLength) : field(f) {};
        //
        //  Add tile to snake at absolute position.
        //
        void add(int x, int y) {};
        //
        //  Change the direction of snake.
        //
        void rotate(int d) {};
        //
        //  Add tiles to tail.
        //
        void grow() {};
        //
        //  Move snake by it direction.
        //
        void shift() {};
};

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander Ananiev, 2020-11-06
@soiran

https://stackoverflow.com/questions/24625401/c-hea...

D
Daniil Demidko, 2020-11-06
@Chronicler

Add a directive to the beginning of each header file#pragma once

M
maaGames, 2020-11-06
@maaGames

forward declaration for classes to do. And read what it is.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question