我可能会用这个完全错误的树,但它确实编译了,它只是崩溃了。我最近两周才在做 C++,主要来自 Java 背景,这不是很广泛!
任何人,我有一个房间类。我想设置4个出口,北,南,东,西。我想创建一个带有 4 个 Room 指针的 setExits() 方法。每个 Room 对象都有一个调用该指针的 goNorth() 等方法。
Room::Room(QString name, QString shortD, QString longD, QImage roomImage)
{
this->name = name;
this->shortD = shortD;
this->longD = longD;
this->roomImage = roomImage;
}
QString Room::shortDescription()
{
return shortD;
}
QString Room::longDescription()
{
return longD;
}
QImage Room::showImage()
{
return roomImage;
}
void Room::setExits(Room *north, Room *south, Room *east, Room *west)
{
this->north = north;
this->south = south;
this->east = east;
this->west = west;
}
Room* Room::goNorth()
{
return north;
}
我正在打电话并像这样进行设置。
void TheIslandMain::createRooms()
{
//Room *forest, *lake; - declare as global in theislandmain.h?
forest = new Room(readRooms("../Island/Rooms/forest.name"), readRooms("../Island/Rooms/forest.short"), readRooms("../Island/Rooms/forest.long"), getImage("../Island/Rooms/forest.jpg"));
//forest->setExits(lake, currentRoom, currentRoom, currentRoom);
lake = new Room(readRooms("../Island/Rooms/lake.name"), readRooms("../Island/Rooms/lake.short"), readRooms("../Island/Rooms/lake.long"), getImage("../Island/Rooms/lake.jpg"));
currentRoom = forest;
}
单击 gui 中的按钮时,我正在使用以下代码。
void TheIslandMain::on_northButton_clicked()
{
ui->roomDesc->clear();
currentRoom = lake;
//currentRoom = currentRoom->goNorth();
ui->actionLabel->setText(currentRoom->shortDescription());
ui->imageArea->setPixmap(QPixmap::fromImage(currentRoom->showImage()));
}
我已经注释掉了我想使用的代码,这就是错误。现在的代码可以正常工作。当我再次取消注释代码时,它会编译文件,但是一旦单击 North 按钮就会出现 255 错误并崩溃。
我什至不确定这是否合法,这只是我正在考虑的事情。我是不是完全找错树了?就像我说的,我只是在学习 C++,实际上我们还没有在课堂上对指针做过任何事情。
我对注释代码的理解是,我将 currentRoom 变量的内存引用更改为 Room 对象中的引用 north,它本身取自主类中定义的引用。
对不起,如果我是愚蠢的!