Проблема программирования на C ++, не удалось назначить указатели на правильные объекты - PullRequest
0 голосов
/ 16 октября 2019

Я работал над проблемой, которая включает в себя квадратный матричный лабиринт размера N с N ^ 2 узлами и 2N (N-1) ребрами, соединяющими вертикальных и горизонтальных соседей. Коды следующие:

//Node.h
#pragma once
#define NULL 0
using namespace std;
class Edge;
class Node {
public:
    int id, row, col;
    Edge* EL, * ER, * EU, * ED;
    vector<int> connected;

    Node(int id, int row, int col);
    Node* get_L();
    Node* get_R();
    Node* get_U();
    Node* get_D();
    void print();
};

//Edge.h
#pragma once
#include "Node.h"
class Edge {
public:
    int id, type;
    bool state;
    Node* N1, * N2;

    Edge(int id, Node n1, Node n2, int type);
    void setState(bool b);
    void print();
};

//Maze.h
#pragma once
#include <vector>
#include "Node.h"
#include "Edge.h"
using namespace std;
class Maze {
public:
    int size;
    vector<Node> nodes;
    vector<Edge> edges;
    Maze(int N);
    void print();
};

//main.cpp
#include <iostream>
#include <vector>
#include "Node.h"
#include "Edge.h"
#include "Maze.h"
Node::Node(int id, int row, int col) {
    this->id = id;
    this->row = row;
    this->col = col;
    this->EL = NULL;
    this->ER = NULL;
    this->EU = NULL;
    this->ED = NULL;
}

Node* Node::get_L() {
    if (EL) {
        return EL->N1;
    }
    else {
        cerr << "Node " << id << "does not have left neighbour.";
    }
}

Node* Node::get_R() {
    if (ER) {
        return ER->N2;
    }
    else {
        cerr << "Node " << id << "does not have right neighbour.";
    }
}

Node* Node::get_U() {
    if (EU) {
        return EU->N1;
    }
    else {
        cerr << "Node " << id << "does not have up neighbour.";
    }
}

Node* Node::get_D() {
    if (ED) {
        return ED->N2;
    }
    else {
        cerr << "Node " << id << "does not have down neighbour.";
    }
}

void Node::print() {
    int l, r, u, d;
    l = EL ? EL->N1->id : -1;
    r = ER ? ER->N2->id : -1;
    u = EU ? EU->N1->id : -1;
    d = ED ? ED->N2->id : -1;
    cout << "Node " << id << " (Row " << row << " Col " << col << "), neighbours <L,R,U,D>: <" << l << "," << r << "," << u << "," << d << ">" << endl;
}

Edge::Edge(int id, Node n1, Node n2, int type) {
    this->id = id;
    this->N1 = &n1;
    this->N2 = &n2;
    this->state = false;
    this->type = type;
}

void Edge::print() {
    if (type == 0) {
        cout << "Horizontal ";
    }
    else {
        cout << "Vertical ";
    }
    cout << "edge " << id << " between <" << N1->id << ", " << N2->id << ">, " << state << endl;
}

void Edge::setState(bool b) {
    this->state = b;
}

Maze::Maze(int N) {
    size = N;

    for (int i = 0; i < N * N; ++i) {
        Node n = Node(i, i / N, i % N);
        nodes.push_back(n);
    }
    int eid = 0;
    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < N - 1; ++j) {
            Node n1 = nodes[i * N + j];
            Node n2 = nodes[i * N + j + 1];
            Edge e = Edge(eid, n1, n2, 0);
            /*
            // &n1 and &n2 retain the same throughout the loop
            cout << &n1 << endl;
            cout << &n2 << endl;
            cout << e.N1->id << "," << e.N2->id << endl;    // This line gives correct result
            e.print();  // Incorrect
            */
            n1.ER = &e;
            n2.EL = &e;
            edges.push_back(e);
            eid++;
        }
    }
    cout << nodes[0].ER << endl;
    for (int i = 0; i < N - 1; ++i) {
        for (int j = 0; j < N; ++j) {
            Node n1 = nodes[i * N + j];
            Node n2 = nodes[i * N + j + 1];
            Edge e = Edge(eid, n1, n2, 1);
            n1.ED = &e;
            n2.EU = &e;
            edges.push_back(e);
            eid++;
        }
    }
}

void Maze::print() {
    cout << size << " x " << size << " Maze" << endl;
    cout << nodes.size() << " nodes:" << endl;
    for (auto& i : nodes) {
        i.print();
    }
    cout << edges.size() << " edges:" << endl;
    for (auto& i : edges) {
        i.print();
    }
}

int main()
{
    Maze m = Maze(8);
    m.print();
}

Однако после компиляции и запуска я обнаружил, что узлы и ребра НЕ связаны друг с другом, как я ожидал. В кодах создания ребер, которые я пытался выяснить причину (см. Прокомментированную часть), я обнаружил, что во всем цикле адреса n1 и n2 всегда остаются одинаковыми. До сих пор понятия не имею, почему это происходит. Пожалуйста, помогите.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...