0

我需要帮助来了解我在以下初始化列表中做错了什么。我正在使用它来初始化一个数据成员对象“RoomResources”,该对象在我的“Room”类中没有默认构造函数:

/* Public methods */
public:

//Constructor - Initialization list with all data member objects that doesn't have a default constructor
Room(const AppDependencies* MainDependencies, RoomId room_id, int width, int height, int disp_width, int disp_height) :

    RoomResources(this->GetAppRenderer())

    {
        //Store the provided initialization data
        this->MainDependencies = MainDependencies;
        this->room_id = room_id;
        this->width = width;
        this->height = height;
        this->disp_width = disp_width;
        this->disp_height = disp_height;

        //Set instance count
        this->instance_count = 0;

        //Load corresponding room resources
        this->Load(room_id);
    }

现在它编译正确,对我来说似乎没问题,但是当我启动我的程序时它会导致崩溃。我知道这个 Init List 是问题所在,因为我尝试不使用它并使用“RoomResources”对象代替默认构造函数,并且我的程序运行良好。

当我调试我的程序时,我收到以下错误:“在“e:\p\giaw\src\pkg\mingwrt-4.0.3-1-mingw32-src\bld/../mingwrt 找不到源文件-4.0.3-1-mingw32-src/src/libcrt/crt/main.c""

似乎某个对象正在尝试调用程序中尚不可用的某些代码或数据,但我在代码中看不到问题。非常感谢你花时间陪伴。

编辑:这是我的 GetAppRenderer 方法的定义:

const SDL_Renderer* Room::GetAppRenderer() {

//Return the const pointer to the App's SDL_Renderer object found in the AppDependencies data member
return this->MainDependencies->MainRenderer;
}
4

1 回答 1

3

您的问题是MainDependencies尚未初始化(因为初始化列表在主构造函数的主体之前GetAppRenderer()执行)所以当您调用时,MainDependencies仍然指向垃圾数据并且您会崩溃。

您可以通过以下方式解决您的问题:

Room(const AppDependencies* MainDependencies, RoomId room_id, int width, int height, int disp_width, int disp_height) :
    // Order is important (GetAppRenderer needs MainDependencies to be initialized)
    MainDependencies(MainDependencies), RoomResources(this->GetAppRenderer())

    {
        //Store the provided initialization data
        this->room_id = room_id;
        this->width = width;
        this->height = height;
        this->disp_width = disp_width;
        this->disp_height = disp_height;

        //Set instance count
        this->instance_count = 0;

        //Load corresponding room resources
        this->Load(room_id);
    }

PS:我会为所有其他成员变量使用初始化列表

于 2014-07-20T14:27:47.683 回答