我在MSVC++ 10中开发了一个应用程序,这是一个Irrlicht项目。该应用程序绘制了两个简单的按钮。在我阅读的教程中,它使用的是一个类MyEventReceiver.。类与主文件位于同一个文件中。我打算移动类MyEventReceiver。我已经这样做了,但我收到了“访问违规错误”。我错过了什么吗?(我的意思是初始化某事)。THe代码如下:
main.cpp
#include <irrlicht.h>
#include <driverChoice.h>
#include "CMyEventReceiver.h"
using namespace irr;
using namespace core;
using namespace video;
using namespace gui;
int main()
{
IrrlichtDevice *device = createDevice(EDT_OPENGL, dimension2d<u32>(640, 480), 16, false, false, false, 0);
if (!device)
return 1;
device->setWindowCaption(L"Irrlicht Test");
IVideoDriver *driver = device->getVideoDriver();
IGUIEnvironment *guienv = device->getGUIEnvironment();
IGUIFont *font = guienv->getFont("../debug/lucida.xml");
guienv->addButton(rect<s32>(250, 20, 250 + 120, 50), 0, GUI_ID_QUIT_BUTTON, L"Exit", L"Exits Program");
guienv->addButton(rect<s32>(400, 20, 400 + 120, 50), 0, GUI_ID_NEW_WINDOW_BUTTON, L"New Window", L"Launches a new Window");
SAppContext context;
context.device = device;
CMyEventReceiver receiver(context);
device->setEventReceiver(&receiver);
while(device->run())
{
driver->beginScene(true, true, SColor(255, 128, 192, 255));
guienv->drawAll();
driver->endScene();
}
device->drop();
return 0;
}CMyEventReceiver.h
#pragma comment(lib, "Irrlicht.lib")
#include <irrlicht.h>
#include <driverChoice.h>
using namespace irr;
using namespace gui;
using namespace core;
struct SAppContext
{
IrrlichtDevice *device;
};
enum
{
GUI_ID_QUIT_BUTTON = 101,
GUI_ID_NEW_WINDOW_BUTTON
};
class CMyEventReceiver : public IEventReceiver
{
public:
CMyEventReceiver(SAppContext &context);
virtual bool OnEvent(const SEvent &e);
private:
SAppContext *sac;
};CMyEventReceiver.cpp
#include "CMyEventReceiver.h"
CMyEventReceiver::CMyEventReceiver(SAppContext &context) {}
bool CMyEventReceiver::OnEvent(const SEvent &e)
{
if (e.EventType == EET_GUI_EVENT)
{
s32 id = e.GUIEvent.Caller->getID();
IGUIEnvironment* guienv = sac->device->getGUIEnvironment();
if (e.GUIEvent.EventType == EGET_BUTTON_CLICKED)
{
if (id == GUI_ID_QUIT_BUTTON)
{
sac->device->closeDevice();
return true;
}
if (id == GUI_ID_NEW_WINDOW_BUTTON)
{
IGUIWindow* window = guienv->addWindow(rect<s32>(100, 100, 300, 200),false, L"New window");
return true;
}
}
}
return false;
}如果我允许文件中的代码(稍微修改一下),它就能工作了。我希望它作为一个单独的文件,它更优雅和更有用。
感谢您的耐心。
Ee Bb
发布于 2014-09-04 17:59:04
看起来,您未能在sac构造函数中分配CMyEventReciever成员变量。
CMyEventReceiver receiver(context); 但是,您的构造函数如下:
CMyEventReceiver::CMyEventReceiver(SAppContext &context) {}基本上是一个“无所事事”的构造函数。
解决办法应该是:
CMyEventReceiver::CMyEventReceiver(SAppContext &context) : sac(&context) {}但是,当对象实际使用指针时,sac依赖于指针来“活动”。因此,IMO似乎是一个有缺陷的设计,但是对于简单的main()程序来说,应该是可以的。
现在,如果程序更复杂,那么您应该使用std::shared_ptr<SAppContext>进行调查,这样指针只有在程序死掉时才会死。
https://stackoverflow.com/questions/25671902
复制相似问题