我需要帮助来理解我在以下初始化列表中做错了什么。我用它初始化一个数据成员对象“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;
}
答案 0 :(得分: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);
}
P.S:我会将init列表用于所有其他成员变量