0

这让我觉得我没有正确使用指针。

主文件

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

void initializeRooms(std::vector<Room*>& rooms);

int main() {
  std::vector<Room*> rooms;
  initializeRooms(rooms);
  Room* r = rooms[0];
  std::cout << "You are in room " << r->getName() << "\n";
  return 0;
}

void initializeRooms(std::vector<Room*>& rooms) {
  Room roomOne {"roomOne"};
  Room roomTwo {"roomTwo"};
  Exit exit { &roomOne, &roomTwo };
  roomOne.addExit(&exit);
  rooms.push_back(&roomOne);
  rooms.push_back(&roomTwo);
}

退出.cpp

class Room;

struct Exit {
  Room* room_one;
  Room* room_two;
};

房间.h

#ifndef ROOM_H
#define ROOM_H

#include <string>
#include <vector>
#include "exit.cpp"

class Room {
private:
  std::string name;
  std::vector<Exit*> exits;

public:
  Room(std::string n): name{n} {

  }

  void addExit(Exit* e);
  std::string& getName();
};

#endif

房间.cpp

#include "room.h"

void Room::addExit(Exit* e) {
  exits.push_back(e);
}

std::string& Room::getName() {
  return name;
}

所以在主文件中,当调用 cout 时,当我运行编译文件时,我只会看到一个不断输出的空行循环。现在保持简单并使用带有clang的makefile

all: build

build: main.o exit.o room.o
    clang++ -std=c++11 main.o exit.o room.o -o simplegame

main.o: main.cpp
    clang++ -std=c++11 -c main.cpp

exit.o: exit.cpp
    clang++ -std=c++11 -c exit.cpp

room.o: room.cpp
    clang++ -std=c++11 -c room.cpp

clean:
    rm -rf *o simplegame
4

1 回答 1

2

撇开你不应该使用原始指针,除非你完全理解你在做什么,下面的代码有问题:

void initializeRooms(std::vector<Room*>& rooms) {
  Room roomOne {"roomOne"};    // this is local object
  Room roomTwo {"roomTwo"};    // this is local object as well 
  Exit exit { &roomOne, &roomTwo }; // exit is also local object and now it holds pointers to other 2 local objects
  roomOne.addExit(&exit);  // same stuff as before
  rooms.push_back(&roomOne); // now you are inserting pointer to local object into vector
  rooms.push_back(&roomTwo); // doing that again
} // now all local objects to this function automatically destroyed and you hold pointers to garbage in rooms

因此,您需要在堆上创建它们,而不是使用本地对象。正如我之前所说,我还建议使用 shared_ptr 和 weak_ptr (稍后是必要的,因为你有循环引用)。

于 2013-09-25T19:43:31.797 回答