gpt4 book ai didi

c++ - 是否可以在一个对象中创建一个对象,该对象的构造函数是在 C++ 中从中创建它的对象

转载 作者:行者123 更新时间:2023-11-28 00:07:50 24 4
gpt4 key购买 nike

我正在学习用 C++ 构建程序,但一直停留在一些基础知识上。我使用 SDL2 从屏幕获取输入并处理屏幕等。我定义了一个对象“Program”和一个对象“EventHandler”。 “EventHandler”处理所有事件(将事件发送到较低级别的对象),但“EventHandler”还应该能够创建一个新窗口,从而访问“Program”。

这意味着我猜想“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;
}

最佳答案

是的,这是可能的,而且您很接近!

this 已经是一个指针。它是 [ not ] 已经是“程序的地址”。
当您编写 &test 时,您将获得一个指向指针的指针,这不是您想要的。

所以你只要写:

new EventHandler(this);

现在我并不是说这种紧耦合是个好主意,但我承认我过去做过类似的事情并且它可以达到可接受的程度。

如果您改为从 Program 中获取您想要共享的任何资源并在两个类之间共享它们,您的设计会更加清晰和简洁。

关于c++ - 是否可以在一个对象中创建一个对象,该对象的构造函数是在 C++ 中从中创建它的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34530134/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com