C++ Pointer GUI QT



我可能会用这个方法完全找到错误的树,但它确实编译了,只是崩溃了。我最近两周才做C++,主要来自Java背景,这并不全面!!

不管怎样,我有房间课。我想设置4个出口,北、南、东、西。我有了创建一个setExits()方法的想法,该方法使用4个Room指针。每个Room对象都有一个调用该指针的goNorth()etc方法。

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,该对象本身取自主类中定义的引用。

对不起,我太笨了!

如果取消注释//forest->setExits(lake, currentRoom, currentRoom, currentRoom);行,很明显会导致问题,因为lake没有初始化。

最新更新