【发布时间】:2015-12-30 13:05:03
【问题描述】:
我正在学习用 C++ 构建程序,但我一直在做一些基本的事情。我使用 SDL2 从屏幕获取输入并处理屏幕等。我定义了一个对象“程序”和一个对象“事件处理程序”。 “EventHandler”处理所有事件(将事件发送到较低级别的对象),但“EventHandler”也应该能够创建一个新窗口,从而访问“程序”。
这意味着我猜“EventHandler”应该与“Program”处于同一级别,并且它们都应该能够相互通信。这可以在 C++ 中完成吗?怎么做?也许还有其他更合乎逻辑的方法。
由于定义类的顺序,下面的代码显然不起作用,而且我自制的“&this”发送“程序”的地址是错误的,但它很好地概述了我正在尝试的内容做。
//handles all events, is in contact with and same level as Program
class EventHandler {
private:
Program *program = NULL;
SDL_Event e;
//inputarrays
const Uint8 *currentKeyStates;
int mouseX = 0;
int mouseY = 0;
bool mousemotion = false;
int mouseButtons[4] = {0, 0, 0, 0};
public:
EventHandler(Program *p) {
program = p;
}
void handleEvents() {
while(SDL_PollEvent(&e) != 0) {
}
}
};
class Program {
private:
EventHandler *eh = NULL;
std::vector<Window> windows;
public:
bool running;
Program() {
//Here the most basic form of the program is written
//For this program we will use SDL2
//Initialize SDL
SDL_Init(SDL_INIT_EVERYTHING);
//This program uses 1 window
Window window(200, 200, 1200, 1000, "");
windows.push_back(window);
//Adds an event handler
eh = new EventHandler(&this);
//now simply run the program
run();
}
void run() {
running = true;
//while (running) {
//}
SDL_Delay(2000);
delete eh;
//Quit SDL subsystems
SDL_Quit();
}
};
int main( int argc, char* args[]) {
Program program;
return 0;
}
【问题讨论】:
-
请edit您的问题并附上minimal reproducible example。请简洁明了。我猜“是否有可能在一个对象中创建一个对象,该对象具有在 c++ 中创建它的对象作为构造函数”可能是最不全面的问题的赢家。
-
你是想说你只是想让这两个类有彼此的指针吗?
-
@YSC 你的意思是我应该把标题改成带有例子的标题?然后标题很长:(。我只是想知道当您在c ++中的对象中创建对象时是否有可能,是否可以将第一个对象(第二个对象是从创建的)提供给第二个对象。
-
我认为你的意思是
Program和EventHandler都应该可以访问std::vector<Window> windows。这意味着windows是一个共享资源。您可以研究享元模式来完成此操作,或者决定其中一个或另一个是windows的最终所有者,只要您仍然能够在需要时将数据传递给另一个。这需要您编写 getter 函数。 -
你好,我在你的对象中放了一个对象...